Friday, December 31, 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.
 
 
C# 
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)
        {
            pg.ClientScript.RegisterStartupScript(pg.GetType(),
                                         "PrintJavaScript", Script);
        }
        HtmlForm frm = new HtmlForm();
        pg.Controls.Add(frm);
        frm.Attributes.Add("runat", "server");
        frm.Controls.Add(ctrl);
        pg.DesignerInitialize();
        pg.RenderControl(htmlWrite);
        string strHTML = stringWrite.ToString();
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.Write(strHTML);
        HttpContext.Current.Response.Write("<script>window.
                                             print();</script>"
);
        HttpContext.Current.Response.End();
    }
}
 
 
VB.NET
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
            pg.ClientScript.RegisterStartupScript(pg.GetType(),
           
"PrintJavaScript", Script)
        End If
        Dim frm As HtmlForm = New HtmlForm()
        pg.Controls.Add(frm)
        frm.Attributes.Add("runat", "server")
        frm.Controls.Add(ctrl)
        pg.DesignerInitialize()
        pg.RenderControl(htmlWrite)
        Dim strHTML As String = stringWrite.ToString()
        HttpContext.Current.Response.Clear()
        HttpContext.Current.Response.Write(strHTML)
        HttpContext.Current.Response.Write("<script>window.print();
                                                        </script>"
)
        HttpContext.Current.Response.End()
    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:
C#
protected void btnPrint_Click(object sender, EventArgs e)
    {
        Session["ctrl"] = Panel1;
        ClientScript.RegisterStartupScript(this.GetType(),
       
"onclick", "<script language=javascript>window.open
                  ('Print.aspx','PrintMe','height=300px,width=300px,
                         scrollbars=1');/script>"
);
    }                
VB.NET
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>window.open    ('Print.aspx',
                              'PrintMe','height=300px,width=300px,
                                             scrollbars=1');</script>"
)
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 :
 
PrintHelper.PrintWebControl(Panel1);
 
Step 5: In the Page_Load event of Print.aspx.cs, add the following code:
C#
 
protected void Page_Load(object sender, EventArgs e)
    {
        Control ctrl = (Control)Session["ctrl"];
        PrintHelper.PrintWebControl(ctrl);
    }
VB.NET
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
                                                            
Handles Me.Load
        Dim ctrl As Control = CType(Session("ctrl"), Control)
        PrintHelper.PrintWebControl(ctrl)
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 - Feedback Form in ASP.NET

  
 
Introduction
We are using System.Web.Mail.SmtpMail to send email in dotnet 1.1 which is obsolete in 2.0.
The
System.Net.Mail.SmtpClient Class will provide us the same feature as that of its
Predecessor.
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();

        Try
        {
            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.To.Add("admin1@yoursite.com");
            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("admin1@yoursite.com")
            Message.CC.Add("admin1@yoursite.com");
            Message.CC.Add("admin2@yoursite.com");

            // You can specify Address directly as string
            Message.Bcc.Add(new MailAddress("admin3@yoursite.com"));
            Message.Bcc.Add(new MailAddress("admin4@yoursite.com"));

            //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
            SmtpClient.Send(message);

            LblStatus.Text = "Email successfully sent.";
        }
        Catch (Exception ex)
        {
            LblStatus.Text = "Send Email Failed." + ex.Message;
        }
      }
A Feedback Form in ASP.NET
--

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
As

Declare @name  varchar(100)
Declare @xtype char(1)
Declare @sqlstring nvarchar(1000)

Declare AllSPViews_cursor cursor for
SELECT sysobjects.name, sysobjects.xtype
FROM sysobjects
  Join sysusers on sysobjects.uid = sysusers.uid
Where OBJECTPROPERTY(sysobjects.id, N'IsProcedure') = 1
  Or OBJECTPROPERTY(sysobjects.id, N'IsView') = 1 and
Sysusers.name ='USERNAME'

Open AllSPViews_cursor

Fetch next from SPViews_cursor into @name, @xtype

While @@fetch_status = 0
  Begin
-- obtain object type if it is a stored procedure or view
   If @xtype = 'P'
      Begin
        Set @sqlstring = 'drop procedure ' + @name
        Exec sp_executesql @sqlstring
        Set @sqlstring = ' '
      End
-- obtain object type if it is a view or stored procedure
   If @xtype = 'V'
      Begin
         Set @sqlstring = 'drop view ' + @name
         Exec sp_executesql @sqlstring
         Set @sqlstring = ' '
      End

    Fetch next from AllSPViews_cursor into @name, @xtype
  End

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

 



 

Thursday, December 30, 2010

How change ASP LinkButton color at client side using CSS

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="http://www.w3.org/1999/xhtml">
<head runat="server">
<style type="text/css" rel="stylesheet">
.customhover a
{
background-color: Purple;
}
.customhover a:hover
{
background-color: Yellow;
}
</style>
</head>
<body>
<form id="Form1" runat="server">
<div>
<div class="customhover">
<asp:LinkButton ID="LinkButton1" runat="server"
CssClass="customhover">Click Here</asp:LinkButton>
</div>
</div>
</form>
</body>
</html>


 

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.
 
C# 
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)
        {
            pg.ClientScript.RegisterStartupScript(pg.GetType(),
                                         "PrintJavaScript", Script);
        }
        HtmlForm frm = new HtmlForm();
        pg.Controls.Add(frm);
        frm.Attributes.Add("runat", "server");
        frm.Controls.Add(ctrl);
        pg.DesignerInitialize();
        pg.RenderControl(htmlWrite);
        string strHTML = stringWrite.ToString();
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.Write(strHTML);
        HttpContext.Current.Response.Write("<script>window.
                                             print();</script>"
);
        HttpContext.Current.Response.End();
    }
}
VB.NET
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
            pg.ClientScript.RegisterStartupScript(pg.GetType(),
           
"PrintJavaScript", Script)
        End If
        Dim frm As HtmlForm = New HtmlForm()
        pg.Controls.Add(frm)
        frm.Attributes.Add("runat", "server")
        frm.Controls.Add(ctrl)
        pg.DesignerInitialize()
        pg.RenderControl(htmlWrite)
        Dim strHTML As String = stringWrite.ToString()
        HttpContext.Current.Response.Clear()
        HttpContext.Current.Response.Write(strHTML)
        HttpContext.Current.Response.Write("<script>window.print();
                                                        </script>"
)
        HttpContext.Current.Response.End()
    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:
C#
protected void btnPrint_Click(object sender, EventArgs e)
    {
        Session["ctrl"] = Panel1;
        ClientScript.RegisterStartupScript(this.GetType(),
       
"onclick", "<script language=javascript>window.open
                  ('Print.aspx','PrintMe','height=300px,width=300px,
                         scrollbars=1');/script>"
);
    }                
VB.NET
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>window.open    ('Print.aspx',
                              'PrintMe','height=300px,width=300px,
                                             scrollbars=1');</script>"
)
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 :
PrintHelper.PrintWebControl(Panel1);
Step 5: In the Page_Load event of Print.aspx.cs, add the following code:
C#
protected void Page_Load(object sender, EventArgs e)
    {
        Control ctrl = (Control)Session["ctrl"];
        PrintHelper.PrintWebControl(ctrl);
    }
VB.NET
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
                                                            
Handles Me.Load
        Dim ctrl As Control = CType(Session("ctrl"), Control)
        PrintHelper.PrintWebControl(ctrl)
End Sub
Well that's it. Try out the sample attached with this article and print any control you desire.