Thursday, December 30, 2010

How to Print in ASP.NET 2.0

One of the most common functionality in any ASP.NET application is to print forms and controls.
There are a lot of options to print forms using client scripts. In the article, we will see how
to print controls in ASP.NET 2.0 using both server side code and javascript.
Step 1: Create a PrintHelper class. This class contains a method called PrintWebControl that
can print any control like a GridView, DataGrid, Panel, TextBox etc. The class makes a call to
window.print() that simulates the print button.
Note: I have not written this class and neither do I know the original author. I will be happy
to add a reference in case someone knows.
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Text;
using System.Web.SessionState;
public class PrintHelper
    public PrintHelper()
    public static void PrintWebControl(Control ctrl)
        PrintWebControl(ctrl, string.Empty);
    public static void PrintWebControl(Control ctrl, string Script)
        StringWriter stringWrite = new StringWriter();
        System.Web.UI.HtmlTextWriter htmlWrite =
new System.Web.UI.HtmlTextWriter(stringWrite);
        if (ctrl is WebControl)
            Unit w = new Unit(100, UnitType.Percentage);
            ((WebControl)ctrl).Width = w;
        Page pg = new Page();
        pg.EnableEventValidation = false;
        if (Script != string.Empty)
                                         "PrintJavaScript", Script);
        HtmlForm frm = new HtmlForm();
        frm.Attributes.Add("runat", "server");
        string strHTML = stringWrite.ToString();
Imports System
Imports System.Data
Imports System.Configuration
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls
Imports System.IO
Imports System.Text
Imports System.Web.SessionState
Public Class PrintHelper
    Public Sub New()
    End Sub
    Public Shared Sub PrintWebControl(ByVal ctrl As Control)
        PrintWebControl(ctrl, String.Empty)
    End Sub
    Public Shared Sub PrintWebControl(ByVal ctrl As Control,
ByVal Script As String)
        Dim stringWrite As StringWriter = New StringWriter()
        Dim htmlWrite As System.Web.UI.HtmlTextWriter =
New System.Web.UI.HtmlTextWriter(stringWrite)
        If TypeOf ctrl Is WebControl Then
            Dim w As Unit = New Unit(100, UnitType.Percentage)
            CType(ctrl, WebControl).Width = w
        End If
        Dim pg As Page = New Page()
        pg.EnableEventValidation = False
        If Script <> String.Empty Then
"PrintJavaScript", Script)
        End If
        Dim frm As HtmlForm = New HtmlForm()
        frm.Attributes.Add("runat", "server")
        Dim strHTML As String = stringWrite.ToString()
    End Sub
End Class
Step 2: Create two pages, Default.aspx and Print.aspx. Default.aspx will
contain the controls to be printed. Print.aspx will act as a popup page to
invoke the print functionality.
Step 3: In your Default.aspx, drag and drop a few controls that you
would like to print. To print a group of controls, place them all in a
container control like a panel. This way if we print the panel using our
PrintHelper class, all the controls inside the panel gets printed.
Step 4: Add a print button to the Default.aspx and in the code behind,
type the following code:
protected void btnPrint_Click(object sender, EventArgs e)
        Session["ctrl"] = Panel1;
"onclick", "<script language=javascript>
Protected Sub btnPrint_Click(ByVal sender As Object, ByVal e As
                               System.EventArgs) Handles btnPrint.Click
        Session("ctrl") = Panel1
        ClientScript.RegisterStartupScript(Me.GetType(), "onclick",
"<script language=javascript>    ('Print.aspx',
End Sub
The code stores the control in a Session variable to be accessed in the pop up page,
Print.aspx. If you want to print directly on button click, call the Print functionality in
the following manner :
Step 5: In the Page_Load event of Print.aspx.cs, add the following code:
protected void Page_Load(object sender, EventArgs e)
        Control ctrl = (Control)Session["ctrl"];
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Handles Me.Load
        Dim ctrl As Control = CType(Session("ctrl"), Control)
End Sub
Well that's it. Try out the sample attached with this article and print any control you desire.

Send Email in ASP.Net 2.0 - Feed back Form


We are using System.Web.Mail.SmtpMail to send email in dotnet 1.1 which is obsolete in 2.0.
System.Net.Mail.SmtpClient Class will provide us the same feature as that of its
This article explains how to use System.Net.Mail namespace to send emails.
Using the code
The HTML Design contains provision to enter sender�s name, email id and his comments. On click
of the send email button the details will be sent to the specified email (Admin).
The Send mail functionality is similar to Dotnet 1.1 except for few changes
  1. System.Net.Mail.SmtpClient is used instead of System.Web.Mail.SmtpMail
    (obsolete in Dotnet 2.0).

  2. System.Net.MailMessage Class is used instead of System.Web.Mail.MailMessage
    (obsolete in Dotnet 2.0)

  3. The System.Net.MailMessage class collects From address as MailAddress object.
  4. The System.Net.MailMessage class collects To, CC, Bcc addresses as MailAddressCollection.
  5. MailMessage Body Format is replaced by IsBodyHtml
The Code is Self explanatory by itself.
protected void btnSendmail_Click(object sender, EventArgs e)
        // System.Web.Mail.SmtpMail.SmtpServer is obsolete in 2.0
        // System.Net.Mail.SmtpClient is the alternate class for this in 2.0
        SmtpClient smtpClient = new SmtpClient();
        MailMessage message = new MailMessage();

            MailAddress fromAddress = new MailAddress(txtEmail.Text, txtName.Text);

            // You can specify the host name or ipaddress of your server
            // Default in IIS will be localhost
            smtpClient.Host = "localhost";

            //Default port will be 25
            smtpClient.Port = 25;

            //From address will be given as a MailAddress Object
            message.From = fromAddress;

            // To address collection of MailAddress
            message.Subject = "Feedback";

            // CC and BCC optional
            // MailAddressCollection class is used to send the email to various users
            // You can specify Address as new MailAddress("")

            // You can specify Address directly as string
            message.Bcc.Add(new MailAddress(""));
            message.Bcc.Add(new MailAddress(""));

            //Body can be Html or text format
            //Specify true if it  is html message
            message.IsBodyHtml = false;

            // Message body content
            message.Body = txtMessage.Text;
            // Send SMTP mail

            lblStatus.Text = "Email successfully sent.";
        catch (Exception ex)
            lblStatus.Text = "Send Email Failed." + ex.Message;

How to drop all tables from a SQL Server 2005 Database

How to drop all tables, all views, and all stored procedures
from a SQL Server 2005 Database?
It may not be a hardcore requirement on day-to-day basis to drop all tables, views and stored
procedures from a SQL Server database within your environment, but it will be handy to have
such a code at your end when such task is required.
There are 2 ways to accomplish this, first using undocumented stored procedure such as
'sp_MSforeachtable' as follows:
exec sp_MSforeachtable "DROP TABLE ? PRINT '? to be dropped' "
Where the results will have all of the tables to be dropped, ok how about
for views & stored procedure then. Here it goes:
create procedure Usp_DropAllSPViews
declare @name  varchar(100)
declare @xtype char(1)
declare @sqlstring nvarchar(1000)
declare AllSPViews_cursor cursor for
SELECT, sysobjects.xtype
FROM sysobjects
  join sysusers on sysobjects.uid = sysusers.uid
where OBJECTPROPERTY(, N'IsProcedure') = 1
  or OBJECTPROPERTY(, N'IsView') = 1 and ='USERNAME'
open AllSPViews_cursor
fetch next from SPViews_cursor into @name, @xtype
while @@fetch_status = 0
-- obtain object type if it is a stored procedure or view
   if @xtype = 'P'
        set @sqlstring = 'drop procedure ' + @name
        exec sp_executesql @sqlstring
        set @sqlstring = ' '
-- obtain object type if it is a view or stored procedure
   if @xtype = 'V'
         set @sqlstring = 'drop view ' + @name
         exec sp_executesql @sqlstring
         set @sqlstring = ' '
    fetch next from AllSPViews_cursor into @name, @xtype
close AllSPViews_cursor
deallocate AllSPViews_cursor

Always test above script within your test or sample database and be satisfied with results to check,
do not directly attempt on a live database that I will not give you any warranty or guarantee on
above task. Do not forget to have a

How to install Turbo C++ on Windows 7 64bit

Few days ago we have posted an article about installing Turbo C++ on 32 bit Windows 7.
Now we are providing step-by-step procedure how to install Turbo C++ on 64 bit Windows 7.
1. Install the software DOSBox ver 0.73 : download here
2. Create a folder,for example „Turbo" (c:\Turbo\)
3. Download and extract TC into the Turbo folder (c:\Turbo\): download here
4. Run the DOSBox 0.73 from the icon located on the desktop:

5. Type the following commands at the command prompt [Z]: mount d c:\Turbo\ [The folder TC is
present inside the folder Turbo]
Now you should get a message which says: Drive D is mounted as a local directory c:\Turbo\
6. Type d: to shift to d:
7. Next follow the commands below:
cd tc
cd bin
tc or tc.exe [This starts you the Turbo C++ 3.0]
8. In the Turbo C++ goto Options>Directories> Change the source of TC to the source directory
[D] ( i.e. virtual D: refers to original c:\Turbo\ . So make the path change to something like
D:\TC\include and D:\TC\lib respectively )

How to start TurboC++ in the DOSBox automatically:
You can save yourself some time by having DOSBox automatically mount your folders and start
Turbo C++:
For DOSBox versions older then 0.73 browse into program installation folder and open the dosbox
.conf file in any text editor. For version 0.73 go to Start Menu and click on "Configuration" and
then "Edit Configuration". Then scroll down to the very end, and add the lines which you want to
automatically execute when DOSBox starts.
Automatically mount and start Turbo C++3.0 in DOSBox ver 0.73:
Scroll down to the very end, and add the lines:
Those commands will be executed automatically when DOSBox starts!
Please note:
Full screen: Alt and Enter
When you exit from the DosBox [precisely when u unmount the virtual drive where Turbo C++ 3.0
has been mounted] all the files you have saved or made changes in Turbo C++ 3.0 will be copied
into the source directory(The directory which contains TC folder)
Don't use shortcut keys to perform operations in TC because they might be a shortcut key for
DOSBOX also . Eg : Ctrl+F9 will exit DOSBOX rather running the code .

Wednesday, December 29, 2010

How change ASP linkbutton control color at client side on Mouse over

Use <div> to with linkbutton to change color. it will not
work if you do not use div or another container control.
use cssclass property except the id of the controls.
<html xmlns="">
<head runat="server">
<style type="text/css" rel="stylesheet">
.customhover a
background-color: Purple;
.customhover a:hover
background-color: Yellow;
<form id="Form1" runat="server">
<div class="customhover">
<asp:LinkButton ID="LinkButton1" runat="server"
CssClass="customhover">Click Here</asp:LinkButton>

How to check the control type at run time

using System;
using System.Drawing;
using System.Windows.Forms;
class CustomCheckBox: Form
     public static void Main()
          Application.Run(new CustomCheckBox());
     public CustomCheckBox()
          int      cyText = Font.Height;
          int      cxText = cyText / 2;
          FontStyle[] afs =
                      { FontStyle.Bold,      FontStyle.Italic,
                        FontStyle.Underline, FontStyle.Strikeout };
          Label label    = new Label();
          label.Parent   = this;
          label.Text     = "Sample Text";
          for (int i = 0; i < 4; i++)
               FontStyleCheckBox chkbox = new FontStyleCheckBox();
               chkbox.Parent = this;
               chkbox.Text = afs[i].ToString();
               chkbox.fontstyle = afs[i];
               chkbox.Location = new Point(2
                         * cxText,     (4 + 3 * i) * cyText / 2);
               chkbox.Size = new Size(12 * cxText, cyText);
               += new EventHandler(CheckBoxOnCheckedChanged);
     void CheckBoxOnCheckedChanged(object obj, EventArgs ea)
          FontStyle fs = 0;
          Label     label = null;
          for (int i = 0; i < Controls.Count; i++)
               Control ctrl = Controls[i];
               if (ctrl.GetType() == typeof(Label))
                    label = (Label) ctrl;
               else if (ctrl.GetType() == typeof(FontStyleCheckBox))
                    if (((FontStyleCheckBox) ctrl).Checked)
                         fs |= ((FontStyleCheckBox) ctrl).fontstyle;
          label.Font = new Font(label.Font, fs);
class FontStyleCheckBox: CheckBox
     public FontStyle fontstyle;

Monday, December 27, 2010

How to enable the 64bit compatibility on IIS6 and IIS7?

Sometimes, you will get the following error after deploying your web application (developed for 64 bit
environment and if you referred to any GAC DLL in your application) on IIS 6 or IIS7.

Could not find the path of
C:\Windows\assembly\GAC_MSIL_<Dll Name>_<GAC ID>\Bin

This error occurs because of your IIS currently not supporting 64bit applications, so you need to enable
the 64bit
compatibility on IIS and you can resolve this by using the following steps on different IIS
versions based your

For IIS6:
Step 1:  Click Start, click Run, type cmd, and then click OK.
Step 2:  Type the following command to disable the 32-bit mode:

cscript %SYSTEMDRIVE%\inetpub\adminscripts\adsutil.vbs 
SET  W3SVC/AppPools/Enable32bitAppOnWin64 0 
Step 3:  Type the following command to install the version of 
ASP.NET 2.0 and to install the script maps at the IIS
root and under:

\aspnet_regiis.exe -i 
Step 4:  Make sure that the status of ASP.NET version 2.0.50727 
        is set to Allowed in the Web service extension list in
 Internet Information Services Manager(if your 
application deployed on windows 2003 or 2008).
For IIS7:
Step 1:  Open the Internet Information Service Manager  
from Start Menu or Control Panel --> Administrative 
Step 2:  Expand  the Application Pools Node then find your Website 
Application Pool then right click on it  then click on 
Advanced Settings, it will popup the settings screen 
here you need to set false for Enable32bitApplication.
This settings may affect your existing 32bit application,
if you get any error on  your 32 applications then you 
reset the above setting and create a new application pool
just like existing on and use itfor 64bit with 
appropriate Enable32bitApplication setting(value must 
be false).