PDF Arabic watermark using MVC and iTextSharp


PDF full page Arabic watermark using MVC and iTextSharp

Download : Source Code

Most of the time we have requirement to generate pdf with water mark to secure and tried to protect from forgery. Here, I will explain how to implement iTextSharp dll in MVC application to create full page watermark in existing pdf.

Step 1:

First of all create MVC web application and install iTextSharp package through Nuget package manager or nugget command mentioned below.
Step 2: 

Add font “ARIAL.TTF” in your solution download from download font or search in google.

Step 3:


Open the controller Home from controller folder in MVC application and add the following ActionResult method in the page.

 public ActionResult GetArabicWaterMarkPdf()
{
// Source File Path
string originalFile = Server.MapPath("~/Attachment/Sample.pdf");

// Destination File path
string destinationpath = Server.MapPath("~/Attachment/SamplewithArabicWaterMark.pdf");

// Read file from file location
PdfReader reader = new PdfReader(originalFile);

//define font size and style
// use specific font for arabic text
BaseFont bf = BaseFont.CreateFont(Server.MapPath("~/fonts/ARIAL.TTF"), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
Font f = new Font(bf, 12);

using (MemoryStream memoryStream = new MemoryStream())
{
using (var pdfStamper = new PdfStamper(reader, memoryStream, '\0'))
{
// Getting total number of pages of the Existing Document
int pageCount = reader.NumberOfPages;

// Create two New Layer for Watermark
PdfLayer layer = new PdfLayer("WatermarkLayer", pdfStamper.Writer);
PdfLayer layer2 = new PdfLayer("WatermarkLayer2", pdfStamper.Writer);

// Loop through each Page

string layerwarkmarktxt = "نموذج"; // define text for
string Layer2warkmarktxt = "خاص وسري";
for (int i = 1; i <= pageCount; i++)
{
// Getting the Page Size
Rectangle rect = reader.GetPageSize(i);

// Get the ContentByte object
PdfContentByte cb = pdfStamper.GetUnderContent(i);


// Tell the cb that the next commands should be "bound" to this new layer

// Start Layer

cb.BeginLayer(layer);


PdfGState gState = new PdfGState();

gState.FillOpacity = 0.1f; // define opacity level
cb.SetGState(gState);

// set font size and style for layer water mark text to generate full page
cb.SetFontAndSize(BaseFont.CreateFont(
BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 10);

List<string> watermarkList = new List<string>();
float singleWaterMarkWidth = cb.GetEffectiveStringWidth(layerwarkmarktxt, false);

float fontHeight = 10;

//Work out the Watermark for a Single Line on the Page based on the Page Width
float currentWaterMarkWidth = 0;
while (currentWaterMarkWidth + singleWaterMarkWidth < rect.Width)
{
watermarkList.Add(layerwarkmarktxt);
currentWaterMarkWidth = cb.GetEffectiveStringWidth(string.Join(" ", watermarkList), false);
}

//Fill the Page with Lines of Watermarks
float currentYPos = rect.Height;

//cb.BeginText();
while (currentYPos > 0)
{
ColumnText.ShowTextAligned(cb, Element.ALIGN_CENTER, new Phrase(string.Join(" ", watermarkList), f), rect.Width / 2, currentYPos, 0, PdfWriter.RUN_DIRECTION_RTL, 1);

currentYPos -= fontHeight;
}


cb.EndLayer();

// End First Layer

//**************************************************************//

// Start Layer 2

// Tell the cb that the next commands should be "bound" to this new layer
cb.BeginLayer(layer2);
cb.SetFontAndSize(bf, 50);
Font fl = new Font(bf, 50);
gState = new PdfGState();
gState.FillOpacity = 0.1f;
cb.SetGState(gState);

cb.SetColorFill(BaseColor.BLACK);

//cb.BeginText();
ColumnText.ShowTextAligned(cb, Element.ALIGN_CENTER, new Phrase(string.Join(" ", Layer2warkmarktxt), fl), rect.Width / 2, rect.Height / 2, 45f, PdfWriter.RUN_DIRECTION_RTL, 1);

// Close the layer
cb.EndLayer();

// End Layer 2
}




}

// Save file to destination location if required
if (System.IO.File.Exists(destinationpath))
{
System.IO.File.Delete(destinationpath);
}
System.IO.File.WriteAllBytes(destinationpath, memoryStream.ToArray());
}

// send file to browse to open it from destination location.
return File(destinationpath, "application/pdf");
}

Now after paste this code we need to call GetWaterMarkPdf() method from view

Open the Index View in Home folder delete all the html text and add one action link like shown as below.

  @Html.ActionLink("Download Arabicwatermark pdf", "GetArabicWaterMarkPdf", "Home", null, new { target = "_blank", @class = "btn btn-primary" })
After adding action link in the view run the web applicaiton and you will see the page looks like below.

Press the download water mark pdf button and then browser will open the watermark pdf file as shown below.

You can see in the background watermark text emboss below the text and image as well as “خاص وسري” written in the middle of the page at 45 degree angle.

Download : Source Code

Advertisements
Posted in Uncategorized | Leave a comment

Full page waternark using MVC and iTextSharp


PDF full page watermark using MVC and iTextSharp

Download : Source Code

Most of the time we have requirement to generate pdf with water mark to secure and tried to protect from forgery. Here, I will explain how to implement iTextSharp dll in MVC application to create full page watermark in existing pdf.

Step 1:

First of all create MVC web application and install iTextSharp package through Nuget package manager or nugget command mentioned below.

Step 2:


Open the controller Home from controller folder in MVC application and add the following ActionResult method in the page.

        public ActionResult GetWaterMarkPdf()
{
// Source File Path
string originalFile = Server.MapPath("~/Attachment/Sample.pdf");

// Destination File path
string destinationpath = Server.MapPath("~/Attachment/SamplewithWaterMark.pdf");

// Read file from file location
PdfReader reader = new PdfReader(originalFile);

//define font size and style
Font font = new Font(FontFamily.HELVETICA, 10);

using (MemoryStream memoryStream = new MemoryStream())
{
using (var pdfStamper = new PdfStamper(reader, memoryStream, '\0'))
{
// Getting total number of pages of the Existing Document
int pageCount = reader.NumberOfPages;

// Create two New Layer for Watermark
PdfLayer layer = new PdfLayer("WatermarkLayer", pdfStamper.Writer);
PdfLayer layer2 = new PdfLayer("WatermarkLayer2", pdfStamper.Writer);

// Loop through each Page

string layerwarkmarktxt = "water mark"; // define text for
string Layer2warkmarktxt = "Confidential";
for (int i = 1; i <= pageCount; i++)
{
// Getting the Page Size
Rectangle rect = reader.GetPageSize(i);

// Get the ContentByte object
PdfContentByte cb = pdfStamper.GetUnderContent(i);


// Tell the cb that the next commands should be "bound" to this new layer

// Start Layer

cb.BeginLayer(layer);


PdfGState gState = new PdfGState();

gState.FillOpacity = 0.1f; // define opacity level
cb.SetGState(gState);

// set font size and style for layer water mark text
cb.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 10);

List<string> watermarkList = new List<string>();
float singleWaterMarkWidth = cb.GetEffectiveStringWidth(layerwarkmarktxt, false);

float fontHeight = 10;

//Work out the Watermark for a Single Line on the Page based on the Page Width
float currentWaterMarkWidth = 0;
while (currentWaterMarkWidth + singleWaterMarkWidth < rect.Width)
{
watermarkList.Add(layerwarkmarktxt);
currentWaterMarkWidth = cb.GetEffectiveStringWidth(string.Join(" ", watermarkList), false);
}

//Fill the Page with Lines of Watermarks
float currentYPos = rect.Height;

//cb.BeginText();
while (currentYPos > 0)
{
ColumnText.ShowTextAligned(cb, Element.ALIGN_CENTER, new Phrase(string.Join(" ", watermarkList), font), rect.Width / 2, currentYPos, 0, PdfWriter.RUN_DIRECTION_RTL, 1);

currentYPos -= fontHeight;
}


cb.EndLayer();

// End First Layer

//**************************************************************//

// Start Layer 2

// Tell the cb that the next commands should be "bound" to this new layer
cb.BeginLayer(layer2);
Font f = new Font(FontFamily.HELVETICA, 50);

gState = new PdfGState();
gState.FillOpacity = 0.1f;
cb.SetGState(gState);

cb.SetColorFill(BaseColor.BLACK);

//cb.BeginText();
ColumnText.ShowTextAligned(cb, Element.ALIGN_CENTER, new Phrase(string.Join(" ", Layer2warkmarktxt), f), rect.Width / 2, rect.Height / 2, 45f, PdfWriter.RUN_DIRECTION_RTL, 1);

// Close the layer
cb.EndLayer();

// End Layer 2
}




}

// Save file to destination location if required
if (System.IO.File.Exists(destinationpath))
{
System.IO.File.Delete(destinationpath);
}
System.IO.File.WriteAllBytes(destinationpath, memoryStream.ToArray());
}

// send file to browse to open it from destination location.
return File(destinationpath, "application/pdf");
}

Now after paste this code we need to call GetWaterMarkPdf() method from view

Open the Index View in Home folder delete all the html text and add one action link like shown as below.

@Html.ActionLink("Download water mark pdf", "GetWaterMarkPdf", "Home",  null,  new { target = "_blank" })
After adding action link in the view run the web applicaiton and you will see the page looks like below.

Press the download water mark pdf button and then browser will open the watermark pdf file as shown below.

You can see in the background watermark text emboss below the text and image as well as “confidential” written in the middle of the page at 45 degree angle.

Download : Source Code

Posted in Asp.Net, C#, iTextSharp, MVC 5.0, Pdf watermark | Leave a comment

Generic Custom Paging and Sorting Using SQL Server and .Net C#


Compared to default paging, custom paging can improve the performance of paging through data by several orders of magnitude, through custom paging large amounts of data can reterive more efficiently than implementing default paging, however, especially when adding sorting to the mix. In this tutorial, we’ll extend the example from the preceding one to include support for sorting and custom paging.

Implementation of Custom paging required following three parts.

  • Pager Control
  • Stored Procedure
  • Web page

Pager Control we need user control for add navigation buttons like move next, pervious, first and last button and later on to join with grid or any other control like repeater etc where we need paging functionality. You should perform following step to create user control. 1. Add user control from Open Visual Studio 2008 and choose File > New Item >User Control and rename the name with “Navigator.ascx” 2. Add four button for navigation move next, pervious, last and first record. 3. I use image button and add images through resource files

 

Code


<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--><%@ Control Language="C#" AutoEventWireup="false" Codebehind="Navigator.ascx.cs"
Inherits
="DMS.Controls.Navigator" %><table border="0" width="100%">
<asp:HiddenField ID="hdnCurrentPage" runat="server" />
<asp:HiddenField ID="hdnTotalPages" runat="server" />
<asp:HiddenField ID="hdnSelectedValue" runat="server" />
<tr>
<td>
<table style="width: 100%">
<tr>
<td align="center">
<asp:ImageButton ID="btnFirst" runat="server" CausesValidation="False"
AlternateText
="First" meta:resourcekey="btnFirstResource1" />  
<asp:ImageButton ID="btnPrevious" runat="server" CausesValidation="False"
AlternateText
="Previous" meta:resourcekey="btnPreviousResource2" />    
<asp:Label ID="Label3" runat="server" Text="Total Records: "
meta:resourcekey
="Label3Resource1" ></asp:Label>
<asp:Label ID="lbltotalItem" runat="server"
meta:resourcekey
="lbltotalItemResource1" ></asp:Label>
<asp:Label ID="Label4" runat="server" Text=", Page "
meta:resourcekey
="Label4Resource1" ></asp:Label>
<asp:Label ID="lblcurrentpage" runat="server" Text="/"
meta:resourcekey
="lblcurrentpageResource1" ></asp:Label>
<asp:Label ID="Label6" runat="server" Text=" of "
meta:resourcekey
="Label6Resource1" ></asp:Label>
<asp:Label ID="lbltotalpages" runat="server"
meta:resourcekey
="lbltotalpagesResource1" ></asp:Label>    
<asp:ImageButton ID="btnNext" runat="server" CausesValidation="False"
AlternateText
="Next" meta:resourcekey="btnNextResource2" />  
<asp:ImageButton ID="btnLast" runat="server" CausesValidation="False"
AlternateText
="Last" meta:resourcekey="btnLastResource2" />
</td>
</tr>
</table>
</td>
</tr></table>

.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, “Courier New”, courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

Code Behind


<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

-->using System;
using System.Data;
using System.Configuration;
using System.Collections;
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.Globalization;

namespace Controls
{
public partial class Navigator : System.Web.UI.UserControl
{
#region Fields
private int _TotalRecord;
private int _PageSize;
#endregion

#region Events
// Delegates event for button click public event DataGridPageChangedEventHandler PageIndexChanged;

#endregion

#region Properties

public int PageSize
{
get { return _PageSize; }
set { _PageSize = value; }
}
public int TotalRecord
{
get { return _TotalRecord; }
set
{
_TotalRecord
= value;
lbltotalItem.Text
= Convert.ToString(_TotalRecord);
}
}
#endregion

#region Data
public void Initialize(int totalRecords, int pageSize)
{
try
{
TotalRecord
= totalRecords;
_PageSize
= pageSize;

if ((_TotalRecord % _PageSize) == 0)
TotalPages
= _TotalRecord / _PageSize;
else
TotalPages
= (_TotalRecord / _PageSize) + 1;

CurrentPage
= 1;

EnableLinks();
}
catch (Exception ex)
{

throw;
}
}
private void EnableLinks()
{
try
{
if (CurrentPage == 1)
{

btnFirst.ImageUrl
= HttpContext.GetGlobalResourceObject("Resource", "FirstImageD").ToString();
btnFirst.Enabled
= false;
btnPrevious.ImageUrl
= HttpContext.GetGlobalResourceObject("Resource", "PreviousImageD").ToString();
btnPrevious.Enabled
= false;


}
else
{
btnFirst.ImageUrl
= HttpContext.GetGlobalResourceObject("Resource", "FirstImageE").ToString();
btnFirst.Enabled
= true;
btnPrevious.ImageUrl
= HttpContext.GetGlobalResourceObject("Resource", "PreviousImageE").ToString();
btnPrevious.Enabled
= true;
}
if (CurrentPage == TotalPages)
{
btnNext.ImageUrl
= HttpContext.GetGlobalResourceObject("Resource", "NextImageD").ToString();
btnNext.Enabled
= false;
btnLast.ImageUrl
= HttpContext.GetGlobalResourceObject("Resource", "LastImageD").ToString();
btnLast.Enabled
= false;
}
else
{
btnNext.ImageUrl
= HttpContext.GetGlobalResourceObject("Resource", "NextImageE").ToString();
btnNext.Enabled
= true;
btnLast.ImageUrl
= HttpContext.GetGlobalResourceObject("Resource", "LastImageE").ToString();
btnLast.Enabled
= true;

}


}
catch (Exception ex)
{

throw;
}
}

#endregion

protected void OnPageIndexChanged(object sender)
{
try
{
if (PageIndexChanged != null)
PageIndexChanged(
this, new DataGridPageChangedEventArgs(sender, CurrentPage));
EnableLinks();
}
catch (Exception ex)
{

throw;
}
}

#region Event Handlers
void btnFirst_Click(object sender, ImageClickEventArgs e)
{
try
{
if (CurrentPage > 1)
CurrentPage
= 1;

OnPageIndexChanged(sender);
//EnableLinks(); }
catch (Exception ex)
{

throw;
}
}
void btnPrevious_Click(object sender, ImageClickEventArgs e)
{
try
{
if (CurrentPage > 1)
CurrentPage
--;

OnPageIndexChanged(sender);
//EnableLinks(); }
catch (Exception ex)
{

throw;
}
}
void btnNext_Click(object sender, ImageClickEventArgs e)
{
try
{
if (CurrentPage < TotalPages)
CurrentPage
++;

OnPageIndexChanged(sender);
}
catch (Exception ex)
{

throw;
}
}
void btnLast_Click(object sender, ImageClickEventArgs e)
{
try
{
if (CurrentPage < TotalPages)
CurrentPage
= TotalPages;

OnPageIndexChanged(sender);
}
catch (Exception ex)
{

throw;
}
}

#endregion

#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
InitializeComponent();
base.OnInit(e);
//CreateControls(); }

///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
private void InitializeComponent()
{
//this.Load += new System.EventHandler(this.Page_Load);
this.btnFirst.Click += new ImageClickEventHandler(btnFirst_Click);
this.btnPrevious.Click += new ImageClickEventHandler(btnPrevious_Click);
this.btnNext.Click += new ImageClickEventHandler(btnNext_Click);
this.btnLast.Click += new ImageClickEventHandler(btnLast_Click);
}


#endregion

#region Hidden Fields
public int CurrentPage
{
get { return int.Parse((!string.IsNullOrEmpty(hdnCurrentPage.Value) ? hdnCurrentPage.Value : "1")); }
set
{
hdnCurrentPage.Value
= Convert.ToString(value);
lblcurrentpage.Text
= Convert.ToString(hdnCurrentPage.Value,CultureInfo.CurrentCulture);
}
}
public int TotalPages
{
get { return int.Parse(hdnTotalPages.Value); }
set
{
hdnTotalPages.Value
= Convert.ToString(value);
lbltotalpages.Text
= hdnTotalPages.Value;
}
}
public string SelectedValue
{
get { return this.hdnSelectedValue.Value; }
set { this.hdnSelectedValue.Value = value; }
}
#endregion
}
}


 Stored Procedure

Create the Table name customer add some major fields like customer name ,Customer ID , Phone No etc  and insert dummy data then we will create the stored procedure for custom paging and sorting


<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

-->/****** Object: StoredProcedure [dbo].[usp_CustomerSearch] Script Date: 11/24/2011 12:34:19 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOCREATE PROCEDURE [dbo].[usp_CustomerSearch]

@Customer_ID int =Null,
@Customer_Name varchar(MAX)=Null,
@Phone_No varchar(MAX)=Null,
@Address varchar(MAX)=Null,
@SortDir VARCHAR(30) = 'ASC',
@SortOrder VARCHAR(max) ='Customer_Name' ,
@PageNumber INT = 1,
@PageSize INT = 25ASBEGIN

SET NOCOUNT ON;

DECLARE @FirstRow INT
DECLARE @LastRow INT
SET XACT_ABORT ON;
DECLARE @SQL NVARCHAR(4000)


SELECT @FirstRow = (@PageNumber - 1) * @PageSize + 1,
@LastRow = @PageSize + (@PageNumber - 1) * @PageSize;

IF @SortORder IS NULL OR @SortOrder = ''
SET @SortOrder = 'DESC';



WITH TempCustomer AS
(
SELECT * , ROW_NUMBER() OVER (ORDER BY

CASE @SortDir
WHEN 'DESC' THEN NULL
ELSE
CASE @SortOrder
WHEN 'Customer_ID' THEN CONVERT(VARCHAR(50),Customer_ID)
WHEN 'Customer_Name' THEN Customer_Name
WHEN 'Phone_No' THEN Phone_No
WHEN 'Address' THEN Address
ELSE Customer_Name
END
END ASC) AS RowNumberAsc,
ROW_NUMBER()
OVER (ORDER BY
CASE @SortDir
WHEN 'ASC' THEN NULL
ELSE
CASE @SortOrder
WHEN 'Customer_ID' THEN CONVERT(VARCHAR(50),Customer_ID)
WHEN 'Customer_Name' THEN Customer_Name
WHEN 'Phone_No' THEN Phone_No
WHEN 'Address' THEN Address
ELSE Customer_Name
END
END DESC) AS RowNumberDesc

FROM (
SELECT [Customer_ID], [Customer_Name], [Phone_No], [Address] FROM [dbo].[Customer] (NOLOCK)

WHERE
1 = 1
AND (LOWER(Customer_Name) LIKE '%'+ @Customer_Name +'%' or @Customer_Name is null)
AND (LOWER(Phone_No) LIKE '%'+ @Phone_No +'%' or @Phone_No is null)
AND (LOWER(Address) LIKE '%'+ @Address +'%' or @Address is null)
AND (LOWER(Customer_ID)= @Customer_ID or @Customer_ID is null)

)
AS TempRow
)


SELECT *,(SELECT COUNT(*) FROM TempCustomer) AS TotalRecords
FROM TempCustomer
WHERE CASE @SortDir WHEN 'DESC' THEN RowNumberDesc ELSE RowNumberAsc END
BETWEEN @FirstRow AND @LastRow
Order By CASE @SortDir
WHEN 'DESC'THEN RowNumberDesc
ELSE RowNumberAsc
END;





ENDGO

In Above stored procedure some fields extra taking as input like SortDir,SortOrder,PageNumber and PageSize.

Fields Details

SortDir : Use for order by direction means “ASC” or “DESC”
SortOrder: Field name on which you want to sort like “Customer_Name” or “Phone_No” etc
PageNumber: Current page number e.g ( when user click next then current page number 2 and so on)
PageSize : Grid page size how many records wants to show in a grid

Aspx Page Code to populate and binding of grid.

Add Grid in a aspx page also add navigator control for created before for paging as shown example given below

HTML Page


<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--><%@ Page Language="C#" AutoEventWireup="false" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default"
EnableEventValidation
="true" %><%@ Register Src="Navigator.ascx" TagName="Navigator" TagPrefix="uc1" %><!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></head><body>
<form id="form1" runat="server">
<div>
</div>
<asp:GridView ID="GridView1" runat="server" AllowSorting="true">
<Columns>
<asp:BoundField DataField="Customer_ID" HeaderText="Customer ID" SortExpression="Customer_ID">
<HeaderStyle Width="10%" />
</asp:BoundField>
<asp:BoundField DataField="Customer_Name" HeaderText="Contact Person" SortExpression="Customer_Name">
<HeaderStyle Width="20%" />
</asp:BoundField>
<asp:BoundField DataField="Address" HeaderText="Address" SortExpression="Address">
<HeaderStyle Width="20%" />
</asp:BoundField>
<asp:BoundField DataField="Phone_No" HeaderText="Phone No" SortExpression="Phone_No" >
<HeaderStyle Width="10%" />
</asp:BoundField>
</Columns>
</asp:GridView>
<uc1:Navigator ID="Navigator1" runat="server" />
</form></body></html>

Code Behind


<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

-->using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Globalization;

namespace WebApplication1
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
}
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
Initializer();

}
private void Initializer()
{
Page.Load
+= new EventHandler(Page_Load);
GridView1.Sorting
+= new GridViewSortEventHandler(GridView1_Sorting);
Navigator1.PageIndexChanged
+= new DataGridPageChangedEventHandler(Navigator1_PageIndexChanged);

}

void Navigator1_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
{
DoSearchAndSetData(Convert.ToString(ViewState[
"sortOrder"]), e.NewPageIndex);
}

void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
if (ViewState["sortdir"] == null)
{
ViewState[
"sortdir"] = "desc";
}
else if (Convert.ToString(ViewState["sortdir"]).ToLower() == "desc")
{
ViewState[
"sortdir"] = "asc";
}
else
{
ViewState[
"sortdir"] = "desc";
}
string[] sort = e.SortExpression.Split('.');

ViewState[
"sortOrder"] = e.SortExpression;



DoSearchAndSetData(e.SortExpression,
1);
}
void DoSearchAndSetData(string sortExperssion, int pageNumber)
{
int _pageSize = 25;
try
{


ModelCustomer objModel
= new ModelCustomer();
objModel.SortOrder
= sortExperssion;
objModel.SortDir
= Convert.ToString(ViewState["sortdir"]);

objModel.PageNo
= pageNumber;
objModel.PageSize
= _pageSize;



List
<ModelCustomer> colModel = new List<ModelCustomer>();
colModel
= DalCustomer.Search(objModel);



if (colModel.Count > 0 && colModel != null)
{
Navigator1.Visible
= true;

if (pageNumber == 1)
this.Navigator1.Initialize(Convert.ToInt32(colModel[0].TotalRecords, CultureInfo.CurrentCulture), _pageSize);
}
else
{
Navigator1.Visible
= false;

}

GridView1.DataSource
= colModel;
GridView1.DataBind();
}
catch (Exception ex)
{

throw;

}
}



}
}

Posted in asp.net C#, Custom Pagign, Custom Sorting, dynamic paging, dynamic sorting, pager control | 9 Comments

Moving,Sorting and Searching Items between two Generic Listbox controls


 

I will explain you how to create user control using two listbox control and moving,filtering and searching items between them.First of all you should add two listbox and add the buttons like given below.

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="ucListBox.ascx.cs" Inherits="ucListBox" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>

<script type="text/javascript" language="javascript">
var ddlText, ddlValue, ddl, lblMesg;
function CacheItems() {

ddlText = new Array();
ddlValue = new Array();
ddl = document.getElementById("<%=lstAvailable.ClientID %>");

for (var i = 0; i < ddl.options.length; i++) {
ddlText[ddlText.length] = ddl.options[i].text;
ddlValue[ddlValue.length] = ddl.options[i].value;
}
}

window.onload = CacheItems;

function FilterItems(value) {

ddl.options.length = 0;
for (var i = 0; i < ddlText.length; i++) {
if (ddlText[i].toLowerCase().indexOf(value) != -1) {
AddItem(ddlText[i], ddlValue[i]);
}
}

if (ddl.options.length == 0) {
AddItem("", "");
}
}

function AddItem(text, value) {

var opt = document.createElement("option");
opt.text = text;
opt.value = value;
ddl = document.getElementById("<%=lstAvailable.ClientID %>");
ddl.options.add(opt);
}

</script>

<table width="100%" border="0">
<tr>
<td style="width: 19%; height: 24px;" runat="server" id="tdd">
<span style="font-size: 8pt"><strong>
<asp:Label runat="server" Text="Search" ID="lblSearch" meta:resourcekey="lblSearchResource1"></asp:Label>
</strong></span>
</td>
<td>
<asp:TextBox ID="txtSearch" runat="server" onkeyup="FilterItems(this.value)" meta:resourcekey="txtSearchResource1"></asp:TextBox><br />
</td>
</tr>
</table>
<table width="60%">
<tr>
<td>
</td>
</tr>
<tr align="center">
<td align="center">
<!-- Start list box-->
<table width="100%">
<tr>
<td valign="top">
<table border="0" width="100%">
<tr>
<td>
<span style="font-size: 8pt"><strong>
<asp:Label runat="server" ID="lblAvailable" Text="Available" meta:resourcekey="lblAvailableResource2"></asp:Label>
</strong></span>
</td>
</tr>
<tr>
<td style="height: 200px">
<asp:ListBox ID="lstAvailable" runat="server" Font-Size="8pt" Height="100%" SelectionMode="Multiple"
Width="300px" meta:resourcekey="lstAvailableResource1"></asp:ListBox>
</td>
</tr>
</table>
</td>
<td align="center" valign="top">
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td>
<br />
</td>
</tr>
<tr>
<td>
<br />
</td>
</tr>
<tr>
<td>
</td>
</tr>
<tr>
<td>
<asp:ImageButton ID="btnAddAll" runat="server" ImageUrl="~/Images/Last.png" CausesValidation="False" />
</td>
</tr>
<tr>
<td>
<asp:ImageButton ID="btnAdd" runat="server" ImageUrl="~/Images/Next.png" CausesValidation="False" />
</td>
</tr>
<tr>
<td>
<asp:ImageButton ID="btnRemove" runat="server" CausesValidation="False" ImageUrl="~/Images/Previous.png" />
</td>
</tr>
<tr>
<td>
<asp:ImageButton ID="btnRemoveAll" runat="server" CausesValidation="False" ImageUrl="~/Images/First.png" />
</td>
</tr>
</table>
</td>
<td valign="top">
<table width="100%">
<tr>
<td>
<span style="font-size: 8pt"><strong>
<asp:Label runat="server" ID="lblAdded" Text="Added" meta:resourcekey="lblAddedResource2"></asp:Label>
</strong></span>
</td>
</tr>
<tr>
<td style="height: 200px">
<asp:ListBox ID="lstAdded" runat="server" Font-Size="8pt" Height="100%" SelectionMode="Multiple"
Width="300px" meta:resourcekey="lstAddedResource1"></asp:ListBox>
</td>
</tr>
<tr>
<td>
</td>
</tr>
</table>
</td>
<td>
<table width="100%">
<tr>
<td>
<asp:ImageButton ID="btnMoveUp" runat="server" CausesValidation="False" ImageUrl="~/Images/MoveUp.png" />
</td>
</tr>
<tr>
<td>
<asp:ImageButton ID="btnMoveDown" runat="server" CausesValidation="False" ImageUrl="~/Images/Movedown.png" />
</td>
</tr>
</table>
</td>
</tr>
</table>
<!-- end list box-->
</td>
</tr>
</table>

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Now let’s, create a method for Moving the items between two ListBox. Here’s the code block below:

using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;

public partial class ucListBox : System.Web.UI.UserControl
{

#region Property
private IList _DataSourceAvailable = null;
private IList _DataSourceAdded = null;
private string _dataTextFieldAvailable = string.Empty;
private string _dataValueFieldAvailable = string.Empty;
private string _dataTextFieldAdded = string.Empty;
private string _dataValueFieldAdded = string.Empty;
private string _availableItemText = "Available Items";
private string _addedItemText = "Added Items";
protected ArrayList arlList = new ArrayList();

/// <summary>
/// Gets or sets the available item text.
/// </summary>
/// <value>The available item text.</value>
///

public string AvailableItemText {
get { return _availableItemText; }
set { _availableItemText = value; }
}

/// <summary>
/// Gets or sets the added items text.
/// </summary>
/// <value>The added items text.</value>
public string AddedItemsText
{
get { return _addedItemText; }
set { _addedItemText = value; }
}

/// <summary>
/// Gets the available items.
/// </summary>
/// <value>The available items.</value>
public ListItemCollection AvailableItems
{
get { return lstAvailable.Items; }
}

/// <summary>
/// Gets the added items.
/// </summary>
/// <value>The added items.</value>
public ListItemCollection AddedItems
{
get { return lstAdded.Items; }
}

/// <summary>
/// Gets or sets the data source for the available items listbox.
/// </summary>
/// <value>The data source for available items.</value>
public IList DataSourceAvailable
{
get { return _DataSourceAvailable; }
set { _DataSourceAvailable = value; }
}

/// <summary>
/// Gets or sets the data source for the added items listbox.
/// </summary>
/// <value>The data source for added items.</value>
public IList DataSourceAdded
{
get { return _DataSourceAdded; }
set { _DataSourceAdded = value; }
}

/// <summary>
/// Gets or sets the data text field available.
/// </summary>
/// <value>The data text field available.</value>
public string DataTextFieldAvailable
{
get { return _dataTextFieldAvailable; }
set { _dataTextFieldAvailable = value; }
}

/// <summary>
/// Gets or sets the data value field available.
/// </summary>
/// <value>The data value field available.</value>
public string DataValueFieldAvailable
{
get { return _dataValueFieldAvailable; }
set { _dataValueFieldAvailable = value; }
}

/// <summary>
/// Gets or sets the data text field added.
/// </summary>
/// <value>The data text field added.</value>
public string DataTextFieldAdded
{
get { return _dataTextFieldAdded; }
set { _dataTextFieldAdded = value; }
}

/// <summary>
/// Gets or sets the data value field added.
/// </summary>
/// <value>The data value field added.</value>
public string DataValueFieldAdded
{
get { return _dataValueFieldAdded; }
set { _dataValueFieldAdded = value; }
}
#endregion

#region Method
protected void Page_Load(object sender, EventArgs e)
{


}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
Initializer();

}
public void Initializer()
{
btnAdd.Click += new ImageClickEventHandler(btnAdd_Click);
btnAddAll.Click += new ImageClickEventHandler(btnAddAll_Click);
btnRemove.Click += new ImageClickEventHandler(btnRemove_Click);
btnRemoveAll.Click += new ImageClickEventHandler(btnRemoveAll_Click);
btnMoveUp.Click += new ImageClickEventHandler(btnMoveUp_Click);
btnMoveDown.Click += new ImageClickEventHandler(btnMoveDown_Click);
lblAdded.Text = this.AddedItemsText;
lblAvailable.Text = this.AvailableItemText;
}



public void BindAvailableList()
{
//Set the Header Text of the Available and Added Items
lblAdded.Text = this.AddedItemsText;
lblAvailable.Text = this.AvailableItemText;

//Bind the Added List Control
lstAvailable.DataSource = this.DataSourceAvailable;
lstAvailable.DataTextField = this.DataTextFieldAvailable;
lstAvailable.DataValueField = this.DataValueFieldAvailable;
lstAvailable.DataBind();
}
public void BindAddedList()
{
//Set the Header Text of the Available and Added Items
lblAdded.Text = this.AddedItemsText;
lblAvailable.Text = this.AvailableItemText;

//Bind the Available List Control
lstAdded.DataSource = this.DataSourceAdded;
lstAdded.DataTextField = this.DataTextFieldAdded;
lstAdded.DataValueField = this.DataValueFieldAdded;
lstAdded.DataBind();
}

public void BindList()
{
//Set the Header Text of the Available and Added Items
lblAdded.Text = this.AddedItemsText;
lblAvailable.Text = this.AvailableItemText;

//Bind the Available and Added List Controls
lstAdded.DataSource = this.DataSourceAdded;
lstAdded.DataTextField = this.DataTextFieldAdded;
lstAdded.DataValueField = this.DataValueFieldAdded;
lstAdded.DataBind();

lstAvailable.DataSource = this.DataSourceAvailable;
lstAvailable.DataTextField = this.DataTextFieldAvailable;
lstAvailable.DataValueField = this.DataValueFieldAvailable;
lstAvailable.DataBind();


#region Remove intersection Record
ArrayList ary = new ArrayList();

for (int i = 0; i < lstAvailable.Items.Count; i++)
{
for (int j = 0; j < lstAdded.Items.Count; j++)
{

if (lstAvailable.Items[i].Value == lstAdded.Items[j].Value)
{
// lstAvailable.RemoveAt(i);
if (!ary.Contains(lstAvailable.Items[i]))
{
ary.Add(lstAvailable.Items[i]);
j = -1;
}
break;
}

}

}
for (int i = 0; i < ary.Count; i++)
{
lstAvailable.Items.Remove(((ListItem)ary[i]));

}

#endregion

ScriptManager.RegisterStartupScript(Page, typeof(Page), "myscript", "CacheItems();", true);
//ScriptManager.RegisterStartupScript(Page, typeof(Page), "myscript", "UploadFileToParent();", true);
}

#endregion

#region Navigation

/// <summary>
/// Add all the selected items from the Available Items to the Added Items
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected void btnAdd_Click(object sender, EventArgs e)
{
if (lstAvailable.SelectedIndex >= 0)
{
for (int i = 0; i < lstAvailable.Items.Count; i++)
{
if (lstAvailable.Items[i].Selected)
{
if (!arlList.Contains(lstAvailable.Items[i]))
arlList.Add(lstAvailable.Items[i]);
}
}
for (int i = 0; i < arlList.Count; i++)
{
if (!lstAdded.Items.Contains((ListItem)arlList[i]))
lstAdded.Items.Add((ListItem)arlList[i]);
lstAvailable.Items.Remove((ListItem)arlList[i]);
}
}
}

/// <summary>
/// Add all the items from the Available items to the Added Items
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected void btnAddAll_Click(object sender, EventArgs e)
{
foreach (ListItem list in lstAvailable.Items)
{
lstAdded.Items.Add(list);
}
lstAvailable.Items.Clear();
}

/// <summary>
/// Moves the Selected items from the Added items to the Available items
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected void btnRemove_Click(object sender, EventArgs e)
{
if (lstAdded.SelectedIndex >= 0)
{
for (int i = 0; i < lstAdded.Items.Count; i++)
{
if (lstAdded.Items[i].Selected)
{
if (!arlList.Contains(lstAdded.Items[i]))
arlList.Add(lstAdded.Items[i]);
}
}
for (int i = 0; i < arlList.Count; i++)
{
if (!lstAvailable.Items.Contains((ListItem)arlList[i]))
lstAvailable.Items.Add((ListItem)arlList[i]);
lstAdded.Items.Remove((ListItem)arlList[i]);
}
}
}

/// <summary>
/// Moves all the items from the Added items to the Available items
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected void btnRemoveAll_Click(object sender, EventArgs e)
{
foreach (ListItem list in lstAdded.Items)
{
lstAvailable.Items.Add(list);
}
lstAdded.Items.Clear();
}

/// <summary>
/// Move item to upwards
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void btnMoveDown_Click(object sender, ImageClickEventArgs e)
{
try
{
int startindex = lstAdded.Items.Count - 1;
for (int i = startindex; i > -1; i--)
{
if (lstAdded.Items[i].Selected)//identify the selected item
{
//swap with the lower item(move down)
if (i < startindex && !lstAdded.Items[i + 1].Selected)
{
ListItem bottom = lstAdded.Items[i];
lstAdded.Items.Remove(bottom);
lstAdded.Items.Insert(i + 1, bottom);
lstAdded.Items[i + 1].Selected = true;
}

}
}
}
catch (Exception ex)
{

}
}

/// <summary>
/// Move Item To down Words
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void btnMoveUp_Click(object sender, ImageClickEventArgs e)
{
try
{
for (int i = 0; i < lstAdded.Items.Count; i++)
{
if (lstAdded.Items[i].Selected)//identify the selected item
{
//swap with the top item(move up)
if (i > 0 && !lstAdded.Items[i - 1].Selected)
{
ListItem bottom = lstAdded.Items[i];
lstAdded.Items.Remove(bottom);
lstAdded.Items.Insert(i - 1, bottom);
lstAdded.Items[i - 1].Selected = true;
}
}
}

}
catch (Exception ex)
{

}
}

#endregion
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Posted in Asp.Net, JavaScript | 10 Comments

FileUpload Control File Type and File Size Validations


Normally we need validation to restrict the user for uploading any kind of files on a Web Server due to security or application requirement also we need to limit the file size to upload on web server.There are many ways to implement validation on file upload control its depend upon application requirement which method you can used .Here I will explain only three validation method you can implement on file upload controls.
 

Upload Control

Validation using Custom Validator on Client Side

You can used custom validator to implement fileupload validation on client side.This validation is faster and easy to implement.

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

<!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>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">

<script language="javascript" type="text/javascript">
function ValidateAttachment(Source, args)
{
var UploadControl = document.getElementById('<%= UploadControl.ClientID %>');

var FilePath = UploadControl.value;

if(FilePath =='')
{
args.IsValid = false;//No file found
}
else
{
var Extension = FilePath.substring(FilePath.lastIndexOf('.') + 1).toLowerCase();

if (Extension == "doc" || Extension == "txt")
{
args.IsValid = true; // Valid file type
}
else
{
args.IsValid = false; // Not valid file type
}
}
}


</script>

<div>
<asp:FileUpload ID="UploadControl" runat="server" />
&nbsp;<asp:Button ID="btnUpload" runat="server" Text="Upload"
onclick="btnUpload_Click" style="height: 26px" />
<br />
<asp:CustomValidator ID="CustomValidator1" runat="server" ClientValidationFunction="ValidateAttachment"
ErrorMessage="Please select valid .doc or .txt file"
onservervalidate="CustomValidator1_ServerValidate"></asp:CustomValidator>
<asp:Label runat="server" ID="StatusLabel" Text="Upload status: " />

</div>
</form>
</body>
</html>

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }Validation using Custom Validator on Server Side

You can also apply validation on server using custom validator its slower than client side but its more secure than client side.

 protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{

string UploadFileName = UploadControl.PostedFile.FileName;

if (string.IsNullOrEmpty(UploadFileName))
{
args.IsValid = false;
}
else
{
string Extension = UploadFileName.Substring(UploadFileName.LastIndexOf('.') + 1).ToLower();

if (Extension == "doc" || Extension == "txt")
{
if (UploadControl.PostedFile.ContentLength < 102400)
{
args.IsValid = true;

}
else
{
args.IsValid = false;
CustomValidator1.ErrorMessage = "File size should be less than 100 kb";
}
}
else
{
args.IsValid = false; // Not valid file type
CustomValidator1.ErrorMessage = "File Type should be .doc or .txt";
}
}



}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }By default, the maximum size of a file to be uploaded to the server using the FileUpload control is around 4MB. You cannot upload anything that is larger than this limit.

Change File Upload Limit

In the web.config file, find a node called <httpRuntime> that looks like the following:

<httpRuntime 
executionTimeout="110"
maxRequestLength="4096"
requestLengthDiskThreshold="80"
useFullyQualifiedRedirectUrl="false"
minFreeThreads="8"
minLocalRequestFreeThreads="4"
appRequestQueueLimit="5000"
enableKernelOutputCache="true"
enableVersionHeader="true"
requireRootedSaveAsPath="true"
enable="true"
shutdownTimeout="90"
delayNotificationTimeout="5"
waitChangeNotification="0"
maxWaitChangeNotification="0"
enableHeaderChecking="true"
sendCacheControlHeader="true"
apartmentThreading="false" />

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

lot is going on in this single node, but the setting that takes care of the size of the files to be uploaded is the maxRequestLength attribute. By default, this is set to 4096 kilobytes (KB). Simply change this value to increase the size of the files that you can upload to the server. If you want to allow 10 megabyte (MB) files to be uploaded to the server, set the maxRequestLength value to 11264, meaning that the application allows files that are up to 11000 KB to be uploaded to the server.

for futher detail check this Working Around File Size Limitations.

Direct Validation on Upload Button

In this method you don’t need to used custom validator you can directly write the code on button click and manually show message using label control.

 protected void btnUpload_Click(object sender, EventArgs e)
{

if (UploadControl.HasFile)
{
try
{
if (UploadControl.PostedFile.ContentType == "image/jpeg")
{
if (UploadControl.PostedFile.ContentLength < 102400)
{
string filename = Path.GetFileName(UploadControl.FileName);
UploadControl.SaveAs(Server.MapPath("~/") + filename);
StatusLabel.Text = "Upload status: File uploaded!";
}
else
StatusLabel.Text = "Upload status: The file has to be less than 100 kb!";
}
else
StatusLabel.Text = "Upload status: Only .doc or .txt files are accepted!";
}
catch (Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}

}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Posted in Asp.Net | 1 Comment

Dynamic Load or Add User Control and Maintain the View State


In this post I will explain you how to add or load user control in a page or any other user control and maintain the view state.Normally we are facing problem when we load user control on button click or any business condition in this case when page will post back control will lost its view state or in other words losing form field values on post back.This is happen because we are adding user control after page Load View State Stage for further detail you should learn asp.net page lifecycle.That means, if we want our dynamic controls to persist view state itself we must add them to the control hierarchy in the page’s Init event.

Here, I will explain the example when we want to add user control on any event.I have two user controls one is Grid view and second I will take login control and load on it into two submit buttons.

 
Adding Reference or Directive on a Webpage
 
The first thing we have to do, is declare our UserControls. It can be done either in each page where it’s used, or globally in the web.config file. There is no performance difference, but when declaring UserControls in the web.config file, the controls have to reside in a different directory than the page(s) using it for further detail check my pervious post Register Custom User Control in Web.Config File

So in the webform, add the following directive:

<%@ Register src="Controls/GridView.ascx" tagname="GridView" tagprefix="uc1" %>

<%@ Register src="Controls/LoginControl.ascx" tagname="LoginControl" tagprefix="uc2" %>

Loading dynamically

For loading user control on a page you should need to drag and drop the place holder where you want to show user control.

<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>

Also add the two buttons to add user control on button click .

<asp:Button ID="btnGrindControl" runat="server" Text="Button" />

<
asp:Button ID="btnLoginControl" runat="server" Text="Button" />

your aspx page look like this,

<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true"

CodeFile="Default.aspx.cs" Inherits="_Default" %>


<%@ Register Src="Controls/GridView.ascx" TagName="GridView" TagPrefix="uc1" %>
<%@ Register Src="Controls/LoginControl.ascx" TagName="LoginControl" TagPrefix="uc2" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">

<asp:Button ID="btnGrindControl" runat="server" Text="Button" />
<asp:Button ID="btnLoginControl" runat="server" Text="Button" />
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>

</asp:Content>

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Code Behind

In the Code Behind of the page, we add the control like this:

PlaceHolder1.Controls.Add(LoadControl("~/UserControl.ascx"));

In order to maintain the Viewstate of user control you should maintain the UserControl complete path and used this path every time on postback and load the control.

using System;

using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
public string ControlPath
{
get
{
if (ViewState["controlPath"] != null)
return Convert.ToString(ViewState["controlPath"]);
else
return null;
}

set
{
ViewState["controlPath"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
LoadUserControl();

}
private void LoadUserControl()
{
if (!string.IsNullOrEmpty(ControlPath))
{
PlaceHolder1.Controls.Clear();
UserControl uc = (UserControl)LoadControl(ControlPath);
PlaceHolder1.Controls.Add(uc);
}
}



protected void btnGrindControl_Click(object sender, EventArgs e)
{
ControlPath = "Controls/GridView.ascx";
LoadUserControl();
}
protected void btnLoginControl_Click(object sender, EventArgs e)
{
ControlPath = "Controls/LoginControl.ascx";
LoadUserControl();
}
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

In above example I create one property name “ControlPath” for maintaining the Url of user control on button click .In LoadUserContol() I am just clearing the placeholder and adding the user control.In postback user control is adding everytime beacuse  user control was added after the page load and view state stage .There are few good articles written by Scott Mitchell on dynamically loading Controls which you will find in the following links:

Conclusion

In this article we saw how to work with dynamic controls so that their values and view state can be correctly persisted across postbacks.

Posted in Asp.Net | 4 Comments

Debugging Asp.net application using XML Serialization


 

Debugging on Test or Production server is very difficult task for developers.First of all developers do not have any rights to touch the Test or Production environment and he received the list of bugs mainly due to data problem on production or Test Server.When developers try to reproduce the bugs on development environment is not possible because data development environment is accurate.So I have found out the solution of this problem through XML Serialization techniques which describe as below:-

In this article I am taking a example of simple Employee Detail.I will explain how we can debug using XML Serialize data.

Example

First I have declare a Employee class and create one method for creating employee details.

public class Employee
{
public string EmployeeName { get; set; }
public string Address { get; set; }
public int MobilNo { get; set; }


public List<Employee> GetEmployees()
{
List<Employee> Emplst = new List<Employee>();

for (int i = 0; i < 5; i++)
{
Employee emp = new Employee();
emp.EmployeeName = "Employee" + "-" + i.ToString();
emp.Address = "Address" + "-" + i.ToString();
emp.MobilNo = 9899 + (i + 2);
Emplst.Add(emp);
}
return Emplst;
}

}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

Now create one page and call the GetEmployee() Method and fill the grid.

 public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Employee objEmp= new Employee();

GridView1.DataSource = objEmp.GetEmployees();
GridView1.DataBind();
}
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Scenario 1

It is very simple code to populate grid from GetEmployees() method but you assume that data is coming from the database and populating the grid and at this time you are facing problem .Now you can track or debug the application with XML Serialization.

protected void Page_Load(object sender, EventArgs e)
{
Employee objEmp = new Employee();

SaveXMLData(objEmp.GetEmployees(), "Employee.XML");
GridView1.DataSource = ReadXMLData<Employee>("Employee.XML");
GridView1.DataBind();
}


#region For Serialization Code

public void SaveXMLData<T>(List<T> list, string fileName)
{
XmlSerializer serializer = new XmlSerializer(typeof(List<T>));
{
TextWriter writer = new StreamWriter(Server.MapPath("~\\XMLFiles") + "\\" + fileName);
serializer.Serialize(writer, list);
writer.Close();

}
}

public List<T> ReadXMLData<T>(string filename)
{
XmlSerializer deserializer = new XmlSerializer(typeof(List<T>));
TextReader textReader = new StreamReader(Server.MapPath("~\\XMLFiles") + "\\" + filename);
List<T> list;
list = (List<T>)deserializer.Deserialize(textReader);
textReader.Close();

return list;
}

#endregion
}

If you see the code on page load I have save the data first into XML and then retrieve and display into the grid due to this every time save data into XML So if  you find any problem in module you will get the XML file from Production or Test Server and Load into development environment through ReadXMLData() method and debug it.

Here is the XML Generate file from the above SaveXMLData() method.

<?xml version="1.0" encoding="utf-8" ?> 
- <ArrayOfEmployee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
- <Employee>
<EmployeeName>Employee-0</EmployeeName>
<Address>Address-0</Address>
<MobilNo>9901</MobilNo>
</Employee>
- <Employee>
<EmployeeName>Employee-1</EmployeeName>
<Address>Address-1</Address>
<MobilNo>9902</MobilNo>
</Employee>
- <Employee>
<EmployeeName>Employee-2</EmployeeName>
<Address>Address-2</Address>
<MobilNo>9903</MobilNo>
</Employee>
- <Employee>
<EmployeeName>Employee-3</EmployeeName>
<Address>Address-3</Address>
<MobilNo>9904</MobilNo>
</Employee>
- <Employee>
<EmployeeName>Employee-4</EmployeeName>
<Address>Address-4</Address>
<MobilNo>9905</MobilNo>
</Employee>
</ArrayOfEmployee>

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Scenario 2

If you are thinking for every time save and read data from XML then application performance will affected so you can change the code like this only when exception will raise it will save the data into xml and then if you want to debug write ReadXMLData() method in a code where you want.

protected void Page_Load(object sender, EventArgs e)
{
try
{
Employee objEmp = new Employee();
GridView1.DataSource = objEmp.GetEmployees();
GridView1.DataBind();
}
catch (Exception ex)
{
SaveXMLData(objEmp.GetEmployees(), "Employee.XML");
throw;
}

}

Conclusion

We have seen in above samples that how we can take advantage of serialization mechanism provided by .Net. In this tutorial I have tried to keep things as simple as possible so you can understand and using the basic concepts of XML serialization for debugging the application. Feel free to share your comments.

Posted in Asp.Net | 1 Comment

Validate different controls on different buttons in a same page


 

Normally developers have a requirement to validate different controls on different buttons in this situation developers face problem when user click on any button all validation will be fire which are not belongs to that button functionality.

ASP.NET V2 introduces a new “ValidationGroup” property on validation and input controls that now makes this possible. This allows page developers to group different controls together for more granular validation behavior.

For example two groups – a “Group1” and a “Group2” of validators. There are then two buttons on the page – when button1 is clicked, the first group of validators will fire. When button2 is clicked, the second group of validators will fire. Postback will be blocked client-side by default if the validation fails:

 

Client Side Validation

<html>

<body>

     <form runat=“server”>

          <asp:textbox id=“TextBox1” runat=“server”/>

          <asp:requiredfieldvalidator ValidationGroup=“Group1” ErrorText=“Need to Fill in Value!” ControlToValidate=“TextBox1” runat=“server”/>

            <asp:textbox id=“TextBox2” runat=“server”/>

            <asp:requiredfieldvalidator ValidationGroup=“Group2” ErrorText=“Need to Fill in Value!” ControlToValidate=“TextBox2” runat=“server”/>

            <asp:button text=“Group1” ValidationGroup=“Group1” runat=“server”/>

            <asp:button text=“Group2” ValidationGroup=“Group2” runat=“server”/>

     </form>

</body>

 

</html>

 

The code given above has two validation groups. The first validation groups is identified as “First” and the second validation group is identified as “Second”. Each validation group has two textboxes, a RequiredField validator and a button. If you look at the code you might see that each control has a property called “ValidationGroup” and its value is set to the name of the validation group to which that control belongs.

Clicking the “Submit1” button initiates the validation of the first group and throws an error message if the TextBox1 is left blank. Since this button belongs to the ‘First’ validation group, it initiates the validaton controls that belongs to that group. Similarly clicking the ‘Submit2’ button throws an error message if the TextBox3 is left blank. Thus the validation groups help in grouping the controls in a single web page allowing you to have separate validations for different controls while allowing you to submit values in a particular group.

 

Server Side Validation

If you want to validate on server side just call page.Validate(“Group Name”) on button click event it will automatically call respective group.You don’t have need to define specific group on html code.

<body>

<form id="form1" runat="server">

<div>

<asp:TextBox ID="TextBox1" Runat="server" ValidationGroup="First"></asp:TextBox>

<asp:TextBox ID="TextBox2" Runat="server" ValidationGroup="First"></asp:TextBox>

<br />

<asp:RequiredFieldValidator ID="RequiredFieldValidator1" Runat="server" ValidationGroup="First"ErrorMessage="TextBox1 should not be blank" ControlToValidate="TextBox1"> </asp:RequiredFieldValidator>

<asp:Button ID="Submit1" Runat="server"  Text="Submit 1" />

 <br /><br /> 

<asp:TextBox ID="TextBox3" Runat="server" ValidationGroup="Second"></asp:TextBox> 

<asp:TextBox ID="TextBox4" Runat="server" ValidationGroup="Second"></asp:TextBox>

<asp:RequiredFieldValidator ID="RequiredFieldValidator2" Runat="server" ErrorMessage=" TextBox3 should not be blank"ControlToValidate="TextBox3" ValidationGroup="Second"></asp:RequiredFieldValidator>

 <asp:Button ID="Submit2" Runat="server"  Text="Submit 2" />

 </div>

</form>

</body> 

 

protected void Submit1_Click(object sender, EventArgs e)

{

 

Page.Validate("First");

 

if(Page.IsValid)

    {

        // Continue

    }

}

 

protected void Submit2_Click(object sender, EventArgs e)

{

 

Page.Validate("Second");

 

if(Page.IsValid)

    {

        // Continue

    }

}




							
Posted in Tips | 1 Comment

Define Access Key In asp.net button control


Flickr Tags: ,

If you want to underline and define the access key in asp.net just like you define in windows application , use the html button element. To produce the same behavior as an asp.net Button control. I set the runat attribute to "server" and use the onclick event to call javascript and onServerClick event to call a server side method.

Here is the code for the page,

<form id="form1" runat="server">

<button id="hbutton1" runat="server" type="submit" accesskey="A" onserverclick="hbutton1_Click" onclick="alert('test');"><u>A</u>dd</button>

</form>

Code-behind, 
 

protected void hbutton1_Click(object sender, EventArgs e)

       {

           Response.Write("hbutton clicked");

       }

When, the page is run, a button is generated with text "Add". When clicked, at first an alert message is shown and then the page postbacks.

Posted in Asp.Net, Tips | 1 Comment

Register Custom User Control in Web.Config File


 

Normally we register any user control or assemblies in page directive of aspx html source if we want to used in any aspx page like.

 

<%@ Register TagPrefix="MyControl" TagName="HeaderControl" Src="Header.ascx" %>

<%@ Register TagPrefix="MyControl" TagName="footerControl" Src="Footer.ascx" %>

<%@ Register TagPrefix="MyAssembly" Assembly="Myassembly" %>

 

 

IF you have header and footer user control and you want to adding on every page or more than one pages then you don’t need to register on every page just register only one time in web.config file and used it multiple time like this way.

<?xml version="1.0"?>

<configuration>

<system.web>

 

        <pages>

        <controls>

        <add tagPrefix="MyControl" src="~/Header.ascx"

        tagName="HeaderControl"/>

        <add tagPrefix="MyControl" src="~/Footer.ascx"

        tagName="footerControl"/>

        <add tagPrefix="MyAssembly" assembly="MyAssembly"/>

        </controls>

        </pages>

        

</system.web>

</configuration>

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Posted in Asp.Net, Tips | 1 Comment