Monthly Archives: August 2013

Export Gridview to PDF in ASP.NET using iTextSharp Library

To export gridview to PDF, we need to refer third party library called “iTextSharp”.

About iTextSharp:

iTextSharp is is a C# port of iText, an open source Java library for PDF generation and manipulation. It can be used to create PDF documents from scratch, to convert XML to PDF  etc.

It can be downloaded from here:

Let’s start coding part now.

1. Once you download iTextSharp library, add a reference to your project as shown below.

I have used version “5.4.3” of iTextSharp in this example.

2. Here is a sample aspx code snippet for gridview. I have used “Northwind” sample database as an example. It can be downloaded from here. Also make sure to set the page attribute EnableEventValidation=”false” otherwise you will see error message like

“RegisterForEventValidation can only be called during Render()”

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ITextSharpPDFGeneration.Default" EnableEventValidation="false"  %>

<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" AutoGenerateColumns="False" DataKeyNames="EmployeeID" AllowPaging="True" AllowSorting="True" HeaderStyle-ForeColor="blue">
 <asp:BoundField DataField="EmployeeID" HeaderText="EmployeeID" ReadOnly="True" InsertVisible="False" SortExpression="EmployeeID"></asp:BoundField>
 <asp:BoundField DataField="FirstName" HeaderText="FirstName" SortExpression="FirstName"></asp:BoundField>
 <asp:BoundField DataField="LastName" HeaderText="LastName" SortExpression="LastName"></asp:BoundField>
 <asp:BoundField DataField="Address" HeaderText="Address" SortExpression="Address"></asp:BoundField>
 <asp:BoundField DataField="City" HeaderText="City" SortExpression="City"></asp:BoundField>
 <asp:BoundField DataField="Country" HeaderText="Country" SortExpression="Country"></asp:BoundField>
 <asp:SqlDataSource runat="server" ID="SqlDataSource1" ConnectionString='<%$ ConnectionStrings:NorthwindConnectionString %>' SelectCommand="SELECT [EmployeeID], [Title], [FirstName], [LastName], [BirthDate], [Address], [City], [Country] FROM [Employees]"></asp:SqlDataSource>

3. Set the connection string in the web.config file.

 <add name="NorthwindConnectionString" connectionString="Data Source=localhost;Initial Catalog=Northwind;Persist Security Info=True;User ID=sa;Password=123456"
 providerName="System.Data.SqlClient" />

4. Add reference to following namespaces in the code behind.

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

5. Add an asp button control to aspx page and on the “onClick” event of the button, write the following code.

 Response.ContentType = "application/pdf";
 Response.AddHeader("content-disposition", "attachment; filename=PDFDoc.pdf");

 StringWriter stringWriter = new StringWriter();
 HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter);

 GridView1.AllowPaging = false;
 GridView1.AllowCustomPaging = false;
 GridView1.AllowSorting = false;


 StringReader stringReader = new StringReader(stringWriter.ToString());
 Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
 HTMLWorker htmlWorker = new HTMLWorker(pdfDoc);
 PdfWriter.GetInstance(pdfDoc, Response.OutputStream);



6. Once it’s done, you need to add a special method to code behind page called “VerifyRenderingInServerForm”.
It is used to avoid the exception like “Control of type must be placed inside a form tag with runat=server.”.
“VerifyRenderingInServerForm” method will make sure that the control is rendered.

public override void VerifyRenderingInServerForm(Control control)
 /* Verifies that the control is rendered */

7. Once all done, rebuild the solution and run it. On the page, When you click on the button, it will export the gridview data to PDF file.

Source Code Download

Github [Repository link] [Direct Link to Rar file]

Free ASP.NET 4.5.1 Sandbox Hosting in DiscountASP.NET Labs

We all know that Microsoft has recently announced ASP.NET 4.5.1 framework. To test the apps on this new framework, DiscountASP Labs is offering a free Beta sandbox for everyone to try.

The reason it’s free, because they want to support the ASP.NET community. They are providing Windows 2012 R2 sandbox platform.

You can sign up for a Sandbox Hosting Account on DiscountASP.NET Labs Site at

Free Sandbox Hosting Account features:

  1. Windows Server 2012 R2
  2. .NET Framework 4.5.1
  3. 50 MB disk space
  4. 50 MB SQL disk space
  5. Uses DiscountASP.NET subdomain
  6. End Date: Oct. 31, 2013

Once you sign up for free account, you will need to validate your email ID.

After validating your email ID, you will be provided information via email like:

  1. WEBSITE Information
  2. FTP Information
  3. MSDeploy Publishing Information (for visual Studio and for IIS Manager)
  4. SQL Server 2012 DATABASE Information

Enjoy hosting your ASP.NET site with SQL Server for free.

jQuery Advantages over Standard Javascript

Sometimes you may ask that “Why jQuery” The answer lies in the advantages of jQuery over standard Javascript.

Advantages of jQuery:

1. Large Javascript library Framework

jQuery enables you to perform hordes of functions in comparison to Javascript.

2. Amazing Documentation and Live Demos

The jQuery website has a great documentation and tutorials available along with a live demos. Even absolute beginner in programming (or jQuery) can learn it very easily.

3. Supports Ajax

jQuery provides full Ajax support where actions can be performed on pages without full postback. jquery has bunch of Ajax methods available.

4. Cross Browser Campatibility

jQuery methods provides cross browser compatibility. This means a code written in jQuery can work in different browsers like Firefox, Chrome, Internet Explorer, Opera etc. So that developer can code easily without worrying about the code output on different browsers.

5. Easy DOM manipulation

jQuery provides you methods for working with the DOM. It handles DOM the way it handles the objects!

6. Ease of use

jQuery is very more easy to use compared to standard Javascript. It uses very simple syntax, It also requires much less lines of code to achieve the same feature in comparison.

7. Strong and Large Open Source community (lots of plugins available)

jQuery is an open source project, it comes with hundreds of plugins available for download to instantly speed up your development process.

Bundling and Minification in ASP.NET 4.5


Aa developer always requires to use multiple Javascript (Js) and CSS files for readability and maintainability of code. But such practice leads to degradation of the overall performance of the website. Because multiple Js and CSS files require multiple HTTP requests from a browser leads to degrade the performance & load time of your web pages.

Bundling and Minification is new feature in ASP.NET 4.5. This feature can help to reduce the size of javascript and css files and make the site perform faster.


This feature makes it easy to combine or bundle multiple files into a single file. You can create CSS, JavaScript and other bundles. Fewer files means fewer HTTP requests and that can improve the page load  performance.


This feature performs a variety of different code optimizations to scripts or CSS, such as removing unnecessary white spaces and comments and shortening variable names to one character.

Bundling and minification is performed at runtime. They identify the user agent (e.g Firefox, Chrome, IE etc) and improve the compression by targeting the user browser (browser specific changes).

Normal Web application approach (Without Bundling and Minification)

1. Let’s start with a sample project, we will add some sample js and css files to our Default.aspx page.

<script src="Scripts/bootstrap.js"></script>
<script src="Scripts/jquery-ui-1.10.3.custom.js"></script>
 <script src="Scripts/jquery-1.10.2.min.js"></script>
 <script src="Scripts/require.js"></script>
 <script src="Scripts/shadowbox.js"></script>
 <script src="Scripts/jquery.mixitup.js"></script>

<link href="Styles/bootstrap-responsive.min.css" rel="stylesheet" />
 <link href="Styles/bootstrap.min.css" rel="stylesheet" />
 <link href="Styles/jquery-ui-1.10.3.custom.css" rel="stylesheet" />
 <link href="Styles/shadowbox.css" rel="stylesheet" />

2. Let’s add a script code on the page. It will display “Page loaded” message on our page.

<script type="text/javascript">
 $(document).ready(function () {
 $('#span1').text('Page loaded');

<h1><b><span id="span1" style="color:blue;"></span></b></h1>

Let’s run this project and inspect it with developer tool plugin of the browser (F12). Switch to Network tab, it will show the timing for assets required by our sample application. As shown below.

3. If you observe Default.aspx page carefully, you can see that client has 15 requests to server, 1.5 KB of data is transfered and it takes 665 ms to complete the request.

Bundling and Minification Approach:

1. First, install the Bundling and Minification Package from NuGet. Open the Package Manager Console, type Install-Package Microsoft.AspNet.Web.Optimization

The command will add references to required assemblies automatically.

2. Create script and style bundles using a class called “BundleConfig”. The following code shows the complete class:

using System.Web.Optimization;

public class BundleConfig
 public static void RegisterBundles(BundleCollection bundles)
 bundles.Add(new ScriptBundle("~/bundles/js").Include(

bundles.Add(new StyleBundle("~/bundles/css").Include(</span>

            //Files can be added to bundle by different ways like shown below
            //bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
            //        "~/Scripts/jquery.unobtrusive*",
            //        "~/Scripts/jquery.validate*"));

            //bundles.Add(new ScriptBundle("~/bundles/WebFormsJs").Include(
            //      "~/Scripts/WebForms/WebForms.js",
            //      "~/Scripts/WebForms/WebUIValidation.js",
            //      "~/Scripts/WebForms/MenuStandards.js",
            //      "~/Scripts/WebForms/Focus.js",
            //      "~/Scripts/WebForms/GridView.js",
            //      "~/Scripts/WebForms/DetailsView.js",
            //      "~/Scripts/WebForms/TreeView.js",
            //      "~/Scripts/WebForms/WebParts.js"));


3. As shown in the code, Wildcard Character (*) can also be used to Select Files.

4. Once a “BundleConfig” class is created, we need to register a bundle in the Application_Start method in the Global.asax.

void Application_Start(object sender, EventArgs e)

5. Once it is done, we need to add reference to these bundles in the Default.aspx page.

<%: System.Web.Optimization.Scripts.Render("~/bundles/js") %>
 <%: System.Web.Optimization.Styles.Render("~/bundles/css") %>

6. Now comment out the javascript and css references from the code.

7. Bundling and minification is enabled or disabled by setting the value of the debug attribute in the compilation Element  in the Web.config file.

 <compilation debug="true" />

8. To enable bundling and minification, set the debug value to “false”. You can override the Web.config setting with the EnableOptimizations property on the BundleTable class.

void Application_Start(object sender, EventArgs e)
 BundleTable.EnableOptimizations = true;

9. Let’s rebuild the solution now and run it and compare the result of Bundling and Minification approach with the normal approach as shown below.

Now, If you observe Default.aspx page carefully implemented with Bundling and Minification, you can see that client has only 7 requests to server, 1.2 KB of data is transfered and it takes 467 ms to complete the request.

Source Code Download:

Github [Repository Link] [Direct Link to Zip file]

New TextMode Properties in ASP.NET 4.5

While working on an open source project called “Link Shortner“, I came to know about a new enumerations of Texbox server control under the property “TextMode”. So let’s discuss about it.

Basically it specifies the behaviour mode of the text box. The TextBoxMode enumeration represents the different display options for textbox server controls.

Note: ASP.NET 4.5 provides full HTML5 support.

e.g If the TextMode of the TextBox control is set to “Password”, then all characters entered in the TextBox control are masked and are not saved in view state.

Following is a list of all the available values for this property and short description in ASP.Net 4.5:

SingleLine Represents single-line entry mode
MultiLine Represents multiline entry mode
Password Represents password entry mode
Color Represents color entry mode
Date Represents date entry mode
DateTime Represents date-time entry mode
DateTimeLocal Represents local date-time entry mode
Email Represents email address entry mode
Month Represents month entry mode
Number Represents number entry mode
Range Represents numeric range entry mode
Search Represents search string entry mode
Phone Represents phone number entry mode
Time Represents time entry mode
Url Represents URL entry mode
Week Represents week entry mode

I request developers to explore the different properties on different browser.

Let’s see some textmode property values:

1. DateTimeLocal

<asp:TextBox ID="textBox1" runat="server" TextMode="DateTimeLocal"></asp:TextBox>

2. Email

<asp:TextBox ID="textBox" runat="server" TextMode="Email"></asp:TextBox>

If you see here, validation was automatically fired when I click on “Submit” button, because of the invalid email address.

3. Month

<asp:TextBox ID="textBox3" runat="server" TextMode="Month"></asp:TextBox>

4. Time

<asp:TextBox ID="textBox5" runat="server" TextMode="Time"></asp:TextBox>

5. Range

<asp:TextBox ID="textBox7" runat="server" TextMode="Range"></asp:TextBox>

6. URL

<asp:TextBox ID="textBox8" runat="server" TextMode="Url"></asp:TextBox>

If you observe here, validation was automatically fired when I click on “Submit” button, because of the ‘url’ is not a valid URL.

7. Week

<asp:TextBox ID="textBox6" runat="server" TextMode="Week"></asp:TextBox>

Hope you understand everything here. Comments and questions are welcome.

Disable Right Click on Web Page and Image in ASP.NET

Sometimes you want to prevent user from right clicking on your web pages or images from being copied. It may be because of some security reasons. You can secure your web pages or images by disabling right click.

Please note that, It is impossible to prevent webpages or images from being stolen/copied completely, since there are so many tools and utilities through which one can copy yours images.

To achieve this, Add the below event handler to the image tag.

Disable right click on images:

1. Javascript Approach:

<img src="" oncontextmenu="return false;" />

2. jQuery Approach:

$('img').bind('contextmenu', function(e){
return false;

jsFiddle example

Disable right click on a web page:

1. Javascript Approach:

<body oncontextmenu="return false;" >

2. jQuery Approach:

return false;

jsFiddle example

Server Busy Error on Microsoft Windows

Most of the time, when you boot windows, you may find this error with a title as “Server Busy” which says:

“This action cannot be completed because the other program is busy. Choose ‘Switch To’ to activate the busy program and correct the problem.”

Most of the time, when you click “Switch to” button, the start menu comes up. When you click “Retry” button, the box comes back up, and when you click “Cancel” button it goes away. (sometimes you will find that “Cancel” button is disabled.) It also goes away after a few minutes on it’s own, if you do not click anything.


You have an installed program which configured to access the internet and perform an operation, such as check for updates.

The ‘server busy’ message is appearing because the program is trying to access the Internet before the connection is completely ready.

Suspected Programs would be an antivirus programiTunes, Java Updater, Samsung kies or any other program that has an update options.

If you find one that meets this description, configure the program to update sometime other than when the computer first starts.


1. In Task Manager, select the ‘Server Busy’ program, right-click and select ‘Go to Process’. This should tell you what program is causing the error. Either uninstall the program or configure it to update sometime other than when computer boots.

2. Run ‘msconfig‘ command and un-check any unnecessary programs, but don’t remove something unless you know what it is. A quick Google search can also help you, if you are not sure about any oddly named processes.

3. Create a new user account on Windows with a fresh user account. The process that is starting will not run anymore. Simply migrate over any documents/pictures/music etc to the new account.

4. If the suspected program (particularly ones that have been recently installed or undergone a significant update.) is difficult to uninstall, then try “System Restore” point to backtrack the recent changes.

5. Check “Event Viewer” entries to find the faulty module that could be causing this issue.

Hope this helps.