Saturday 31 December 2011

Complete code For HtmlReport and Convert Word,Excel,Pdf with Print

Default.aspx(Design)-:


Note: Add iTextsharp Dll in Your Project.It can be downloded from   here


 http://sourceforge.net/projects/itextsharp/files/latest/download


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script language="javascript" type="text/javascript">
        function Print() {
            document.body.offsetHeight; window.print();
        }
    </script>
 
</head>
<body>
    <form id="form1" runat="server">
    <div>    
    <table width="100%" align="center">
     <tr>
      <td width="25%"></td><td width="25%"></td><td width="25%"></td>
      <td width="25%">
          <asp:ImageButton ID="ImgExcel" runat="server" ImageUrl="~/Image/excel.jpg"
              Width="50px" Height="50px" onclick="ImgExcel_Click" />
          <asp:ImageButton ID="ImgWord" runat="server" ImageUrl= "~/Image/word.jpg"
              Width="50px" Height="50px" onclick="ImgWord_Click" />
          <asp:ImageButton ID="ImgPdf" runat="server" ImageUrl= "~/Image/pdf.jpg"
              Width="50px" Height="50px" onclick="ImgPdf_Click" />
          <asp:ImageButton ID="ImgPrint" runat="server" ImageUrl="~/Image/print.gif" OnClientClick="Print()"
              Width="50px" Height="50px"/></td>
     </tr>
    </table>
        <asp:Label ID="LblView" runat="server" Text=""></asp:Label>
    </div>
    </form>
</body>
</html>


Default.aspx.cs(Code):

Add Following Namespace in your C# Page.


using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;

Add Following Code In Page Load for Html Report Generation.


protected void Page_Load(object sender, EventArgs e)
    {
        DataSet ds = new DataSet();
        ds.ReadXml(Server.MapPath("~/App_Data/XMLFile.xml"));

        StringBuilder strHtmlContent = new StringBuilder();
        strHtmlContent.Append("<h2 align='center'><b><font family='verdana'><u>Student Information</u></font></b></h1>".ToString());
        strHtmlContent.Append("<br/>".ToString());
        strHtmlContent.Append("<table align='center' width='50%' border='0' style='font-family:verdana'>".ToString());
        strHtmlContent.Append("<tr><td width='20%'>College Name:</td><td width='20%'>A.S COLLEGE,TIRTOL</td><td width='20%'>Date:</td><td width='20%'>30/12/2011</td><td width='20%' rowspan='3'></td></tr>".ToString());
        strHtmlContent.Append("<tr><td width='20%'>College Address:</td><td width='20%'>Tirtol,Jagatsinfhpur</td><td width='20%'>Place:</td><td width='20%'>Tirtol</td></tr>".ToString());
        strHtmlContent.Append("<tr><td width='20%'>Year:</td><td width='20%'>2011</td><td width='20%'></td><td width='20%'></td></tr>".ToString());
        strHtmlContent.Append("</table>".ToString());
        strHtmlContent.Append("<table align='center' width='50%' border='1' style='font-family:verdana'>".ToString());
        strHtmlContent.Append("<tr style='font-weight:Bold'><b><td width='40%'>Name</td><td width='35%'>Country</td><td width='35%'>City</td></b></tr>".ToString());
        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
        {
            strHtmlContent.Append("<tr><td width='40%'>" + ds.Tables[0].Rows[i][0].ToString() + "</td><td width='35%'>" + ds.Tables[0].Rows[i][1].ToString() + "</td><td width='35%'>" + ds.Tables[0].Rows[i][2].ToString() + "</td></tr>".ToString());
        }
        strHtmlContent.Append("</table>".ToString());
        strHtmlContent.Append("<table align='center' width='50%'  style='font-family:verdana;font-weight:Bold'>".ToString());
        strHtmlContent.Append("<tr><td colspan='3' align='right'>Signture:</td></tr>".ToString());
        strHtmlContent.Append("<tr><td colspan='3' align='right'>Date:</td></tr>".ToString());
        //strHtmlContent.Append("<tr><td colspan='3' align='center'><input type='button' value='PRINT' runat='server' onClick='Print()' ID='btnprint'>&nbsp;&nbsp;&nbsp;<input type='button' value='WORD' runat='server' ID='btnword' onClick='btnword_Click'></td></tr>".ToString());
        strHtmlContent.Append("</table>".ToString());
        LblView.Text = strHtmlContent.ToString();
    }






 protected void ImgWord_Click(object sender, ImageClickEventArgs e)
    {
        string attachment = "attachment; filename=Contacts.doc";
        Response.ClearContent();
        Response.AddHeader("content-disposition", attachment);
        Response.ContentType = "application/msword";
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        LblView.RenderControl(htw);
        Response.Write(sw.ToString());
        Response.End();
    }









 protected void ImgExcel_Click(object sender, ImageClickEventArgs e)
    {
        string attachment = "attachment; filename=GridviewExport.xls";
        Response.ClearContent();
        Response.AddHeader("content-disposition", attachment);
        Response.ContentType = "application/ms-excel";
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        LblView.RenderControl(htw);
        Response.Write(sw.ToString());
        Response.End();
    }







 protected void ImgPdf_Click(object sender, ImageClickEventArgs e)
    {
        Response.ContentType = "application/pdf";
        Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.pdf");
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        //GridView1.AllowPaging = false;
        //GridView1.DataBind();
        //GridView1.RenderControl(hw);
        LblView.RenderControl(hw);
        StringReader sr = new StringReader(sw.ToString());
        Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
        HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
        PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
        pdfDoc.Open();
        htmlparser.Parse(sr);
        pdfDoc.Close();
        Response.Write(pdfDoc);
        Response.End();

    }









Add Following code in JavaScript :


 function Print() {
            document.body.offsetHeight; window.print();
        }

Page View:



Wednesday 28 December 2011

C#/.NET Five Little Wonders That Make Code Better (1 of 3)


I Found a great link on c#   that I'd like to share..Check out this link.

C#/.NET Five Little Wonders That Make Code Better (1 of 3)

Best Practices for Speeding Up Your Web Site

Today I found a greate article for  best practices for making web pages fast.The list includes 34 best practices divided into 7 categories.

 1) Content

    * Minimize HTTP Requests
    * Reduce DNS Lookups
    * Avoid Redirects
    * Make Ajax Cacheable
    * Post-load Components
    * Preload Components
    * Reduce the Number of DOM Elements
    * Split Components Across Domains
    * Minimize the Number of iframes

2) Server

    * Use a Content Delivery Network
    * Add an Expires or a Cache-Control Header
    * Gzip Components
    * Configure ETags
    * Flush the Buffer Early
    * Use GET for AJAX Requests

3) CSS

    * Put Stylesheets at the Top
    * Avoid CSS Expressions
    * Choose over @import
    * Avoid Filters

4) Javascript

    * Put Scripts at the Bottom
    * Make JavaScript and CSS External
    * Minify JavaScript and CSS
    * Remove Duplicate Scripts
    * Minimize DOM Access
    * Develop Smart Event Handlers

5) Cookie

    * Reduce Cookie Size
    * Use Cookie-free Domains for Components

6) Images

    * Optimize Images
    * Optimize CSS Sprites
    * Don’t Scale Images in HTML
    * Make favicon.ico Small and Cacheable

7) Mobile

    * Keep Components under 25K
    * Pack Components into a Multipart Document

For details check out this 

How to enlarge image on mouseover in asp.net using jquery


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Img_Enlarge.aspx.cs" Inherits="Img_Enlarge" %>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <script type="text/javascript" src="Scripts/jquery-1.4.1.js"></script>
    <style type="text/css">
        .thumbnail
        {
            height: 100px;
            width: 100px;
            position: relative;
        }
        .image
        {
            position: relative;
            width: 400px;
            height: 250px;
        }
    </style>
    <script language="javascript" type="text/javascript">
        $(document).ready(function () {
            $(".thumbnail").mouseover(function () {
                $(".thumbnail").css("opacity", ".5");
                $(this).animate({ opacity: 1.0 });
                $("#imgContainer").append("<img class='image' src='" + $(this).attr("src") + "' />");


            });
            $(".thumbnail").mouseout(function () {
                $(".thumbnail").css("opacity", "1.0");
                $(".image").remove();
            });
        });
       
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    </div>
    </form>
    <div align="center">
        <img alt="" class="thumbnail" src="Image/Chrysanthemum.jpg"/>
        <img class="thumbnail" src="Image/Desert.jpg" alt="" />
        <img class="thumbnail" src="Image/Hydrangeas.jpg" alt="" />
        <img class="thumbnail" src="Image/Jellyfish.jpg" alt="" />
        <div id="imgContainer">
        </div>
    </div>
</body>
</html>







How To Clear All Textboxes and Dropdownlist in ASP.NET




protected void BtnCancel_Click(object sender, EventArgs e)
    {
        Control myForm = Page.FindControl("iii");

        foreach (Control ctl in myForm.Controls)
        {
            if (ctl.GetType().ToString().Equals("System.Web.UI.WebControls.TextBox"))
            {
                ((TextBox)ctl).Text = "";
            }
            else if (ctl.GetType().ToString().Equals("System.Web.UI.WebControls.DropDownList"))
            {
                ((DropDownList)ctl).ClearSelection();
            }
        }
    }




How To Convert ArrayList To DataSet


How to convert an arraylist to dataset or datatable so that I can filter or make a select distinct from it or Bind it to Gridview.
public DataSet ConvertArrayListToDataSet()
   {
       DataSet dsTemp = new DataSet();
       DataTable Tables = new DataTable();
       dsTemp.Tables.Add(Tables);

       dsTemp.Tables[0].Columns.Add("val", System.Type.GetType(
       "System.String"));

       foreach (string str in arraylistcontainer)
       {
           if (str != string.Empty)
           {
               DataRow myRow = dsTemp.Tables[0].NewRow();
               myRow[0] = str;
               dsTemp.Tables[0].Rows.Add(myRow);
           }

       }
   }

JQuery lightbox image slideshow gallery in asp.net


Introduction:

In this article I will explain how to create lightbox image slideshow in asp.net using JQuery.


Description: 
  
In previous post I explained about Ajax SlideshowExtender sample to display images slideshow. Now in this article I will explain how to create lightbox image slideshow in asp.net using JQuery. In many websites generally we will see different types of slideshows like whenever we click on image that is automatically open with lightbox effect and we have a chance to see all the remaining images by press next or previous options in slideshow. All these Slideshows are implemented by using JQuery plugins. After seen those slideshows I decided to write post to use JQuery plugins to implement beautiful slideshown in asp.net. 


To implement this one I am using  previous post insert and display images from folder based on imagepath in database because in that post I explained clearly how to insert images into our project folder and insert images path into database and display images in gridview from images folder based on Images path in database.
To implement slideshow concept first design table in your database as shown below
Column Name
Data Type
Allow Nulls
ID
int(set identity property=true)
No
ImageName
varchar(50)
Yes
Description
nvarchar(max)
Yes

After completion of table creation Open Visual Studio and create new website after that right click on your website and add new folder and give name as SlideImages because here I used same name for my sample if you want to change folder name then you need to change the Slideimages folder name in your code behind also after that write the following code in your aspx page  


<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Display Images Slideshow in asp.net using JQuery</title>
<link rel="stylesheet" href="lightbox.css" type="text/css" media="screen" />
<script type="text/javascript" src="prototype.js"></script>
<script type="text/javascript" src="scriptaculous.js?load=effects"></script>
<script type="text/javascript" src="lightbox.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<table align="center">
<tr>
<td colspan="2" height="200"></td>
</tr>
<tr>
<td>
Upload Image:
</td>
<td>
<asp:FileUpload ID="fileuploadimages" runat="server" />
</td>
</tr>
<tr>
<td>
Enter Image Desc:
</td>
<td>
<asp:TextBox ID="txtDesc" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" onclick="btnSubmit_Click" />
</td>
</tr>
<tr>
<td colspan="2">
<asp:DataList ID="dlImages" runat="server" RepeatColumns="3" CellPadding="5">
<ItemTemplate>
<a id="imageLink" href='<%# Eval("ImageName","~/SlideImages/{0}") %>' title='<%#Eval("Description")%>' rel="lightbox[Brussels]" runat="server" >
<asp:Image ID="Image1" ImageUrl='<%# Bind("ImageName", "~/SlideImages/{0}") %>' runat="server"Width="112" Height="84" />
</a>
</ItemTemplate>
<ItemStyle BorderColor="Brown" BorderStyle="dotted" BorderWidth="3px" HorizontalAlign="Center"
VerticalAlign="Bottom" />
</asp:DataList>
</td>
</tr>
</table>
<br />
</div>
</form>
</body>
</html>
If you observe above code in header section I added some of script files and css file by using those files we will get lightbox effect slideshow. To get those files download attached sample code and use it in your application.

Another thing here we need to know is href link

<a href='<%# Eval("ImageName","~/SlideImages/{0}") %>' id="imageLink" title='<%#Eval("Description")%>' rel="lightbox[Brussels]" runat="server" >
In above tag I added rel="lightbox" this tag is used to active lightbox title this attribute is used to display image caption. If we have set of related images to group we need to include group name in between square brackets in rel attribute like rel="lightbox[Brussels]"

After completion of aspx page design add following namespaces in code behind 

C# Code

using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
After add namespace write the following code


SqlConnection con = new SqlConnection("Data Source=SureshDasari;Initial Catalog=MySampleDB;Integrated Security=true");
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
BindDataList();
}
}
protected void BindDataList()
{
con.Open();
//Query to get ImagesName and Description from database
SqlCommand command = new SqlCommand("SELECT ImageName,Description from SlideShowTable", con);
SqlDataAdapter da = new SqlDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
dlImages.DataSource = dt;
dlImages.DataBind();
con.Close();
}

protected void btnSubmit_Click(object sender, EventArgs e)
{
//Get Filename from fileupload control
string filename = Path.GetFileName(fileuploadimages.PostedFile.FileName);
//Save images into SlideImages folder
fileuploadimages.SaveAs(Server.MapPath("SlideImages/" + filename));
//Open the database connection
con.Open();
//Query to insert images name and Description into database
SqlCommand cmd = new SqlCommand("Insert into SlideShowTable(ImageName,Description) values(@ImageName,@Description)", con);
//Passing parameters to query
cmd.Parameters.AddWithValue("@ImageName", filename);
cmd.Parameters.AddWithValue("@Description", txtDesc.Text);
cmd.ExecuteNonQuery();
//Close dbconnection
con.Close();
txtDesc.Text = string.Empty;
BindDataList();
}

VB.NET Code

Imports System.Data
Imports System.Data.SqlClient
Imports System.IO

Partial Class _Default
Inherits System.Web.UI.Page
Private con As New SqlConnection("Data Source=SureshDasari;Initial Catalog=MySampleDB;Integrated Security=true")
Protected Sub Page_Load(ByVal sender As ObjectByVal e As EventArgs) Handles Me.Load
If Not IsPostBack Then
BindDataList()
End If
End Sub
Protected Sub BindDataList()
con.Open()
'Query to get ImagesName and Description from database
Dim command As New SqlCommand("SELECT ImageName,Description from SlideShowTable", con)
Dim da As New SqlDataAdapter(command)
Dim dt As New DataTable()
da.Fill(dt)
dlImages.DataSource = dt
dlImages.DataBind()
con.Close()
End Sub

Protected Sub btnSubmit_Click(ByVal sender As ObjectByVal e As EventArgs)
'Get Filename from fileupload control
Dim filename As String = Path.GetFileName(fileuploadimages.PostedFile.FileName)
'Save images into SlideImages folder
fileuploadimages.SaveAs(Server.MapPath("SlideImages/" & filename))
'Open the database connection
con.Open()
'Query to insert images name and Description into database
Dim cmd As New SqlCommand("Insert into SlideShowTable(ImageName,Description) values(@ImageName,@Description)", con)
'Passing parameters to query
cmd.Parameters.AddWithValue("@ImageName", filename)
cmd.Parameters.AddWithValue("@Description", txtDesc.Text)
cmd.ExecuteNonQuery()
'Close dbconnection
con.Close()
txtDesc.Text = String.Empty
BindDataList()
End Sub
End Class
Now run your application and enter images description and upload some of the images using upload control after that your page should be like this  



Now click on any image slideshow will begin with lightbox effect. Check the below demo

If you observe above image in this lightbox slideshow we are having different features like auto playing,navigate images using ‘prev’ and ‘next’ links, show image description and stop slideshow options and many more.

In slideshow we can navigate by using keyboard shortcuts

f- first image
l- last image
x and c to close
left arrow and p for previous image
right arrow and n for next image

Download sample code attached