Monday, May 25, 2009

How to enable or disable LinkButton in Javascript.

we can make Linkbutton Enable\Disable in Javascript. normally disabled='disabled' attribute works only in internet explorer not in Mozilla. to resolve this problem we can develope a javascript function Which perform this.

(1) Suppose we have a LinkButton

<asp:LinkButton ID="lnkTest" runat="server" CommandArgument="1" CommandName="1x"

(2)Style for enabling and Disabling is

cursor: pointer;
cursor: default;
color: Gray;

(3) and javascript fiuction is

<script language="javascript">
function EnableLinkButton(ID,flag)
document.getElementById(ID).onclick=function(){return flag;};
EnableLinkButton('<%= lnkTest.ClientID %>',false);

Calling above javascript function we can Enable or disable LinkButton from Javascript.


Friday, May 22, 2009

Scrolling div at fixed position on scrolling of window.

we can scroll div element and keep its location fixed by calculating its new left and top properties
and moving it to that position..
we have to find out new value for top style of that div element.
here is the script for moving div element to the new position..

<script type="text/javascript" language="javascript">
function FloatElement()
var myfloaingTop=500;

here is the div element.

<div id="myfloaing" style="position: absolute; width: 200px; height: 50px; left: 500px;
top: 0px; padding: 16px; background: #FFFFFA; border: 2px solid #2266AA">

My Floating div.


Tuesday, May 19, 2009

Using extenstion method with user define class.

we can convert fields and properties of any class as xml data using extension methods in c# 3.5.
to convert fields and properties as xml data we can use custom logic or we can use XmlSerializer to convert whole object as xml file.
here is the implementation of Toxml and SerilizeToXml method on user defined class Automobile.

Put this class and extension methods calss in App_Code folder as (Automobile.cs)

using System;
using System.Linq;
using System.Xml.Linq;
using System.Reflection;
using System.Xml.Serialization;
using System.IO;
/// Summary description for Automibile

public class Automobile
#region Fields
public string Name;
public DateTime LaunchDate;
public int Average;
public string[] ments;
#region Properties
public int GetAverage
return Average;
Average = value;
public static class AutomobileExtensions
#region Automobile Extension methods
public static string ToXml(this Automobile entity)
Type t = entity.GetType();
PropertyInfo[] pInfo = t.GetProperties();
FieldInfo[] fInfo = t.GetFields();
var fs = from f in fInfo
select new { Name = f.Name, value = f.GetValue(entity) };
var ps = from p in pInfo
select new { Name = p.Name, value = p.GetValue(entity, null) };
var str = new XElement(t.Name, from n in fs.Union(ps)
select new XElement(n.Name, n.value));
return str.ToString();
public static string SerilizeToXml(this Automobile entity)
XmlSerializer xmlSerilizer = new XmlSerializer(entity.GetType());
StringWriter strWriter = new StringWriter();
xmlSerilizer.Serialize(strWriter, entity);
return strWriter.ToString();

Calling extension methods.

protected void Page_Load(object sender, EventArgs e)
Automobile Honda = new Automobile();
Honda.Name = "Delux";
Honda.LaunchDate = DateTime.Now;
Honda.Average = 60;
Honda.ments = new string[] { "H", "A" };


Friday, May 15, 2009

Bind User define Enum type with Databound controls.

Some time we need to bind User defined datatype Enum with databound controls like DropDownList, ListControl etc. we can do this using two method provided by Enum class.


as name suggests this two methods used to iterate over name and values contained in enumeration.

Now let's see how to bind enum with dropdownlits with example.

I have my EnumType. eg.

public enum DeviceTypes
Mechanical = 4,
Analog = 2,
Digital = 5

I Want to bind DeviceTypes enumeration with dropdownlist.

there are many ways . i Used Linq to perform this task.

here is my C# code to bind DeviceTypes enum with dropdownlist..

var AllEnumsMembersValues = Enum.GetValues(typeof(DeviceTypes)).Cast();
var AllEnumValuesWithNames = from item in AllEnumsMembersValues
select new { ID = item, Name = (Enum.GetName(typeof(DeviceTypes), item)) };
DropDownList ddlDevices = new DropDownList();
ddlDevices.DataSource = AllEnumValuesWithNames;
ddlDevices.DataValueField = "ID";
ddlDevices.DataTextField = "Name";


How to find out space used by Tables and it's Indexes.

In sql server we can find out how much space used by table in databse.
this is possible using stored procedure called sp_spaceused.

this Build int SP take table name as argument and Retrns Columns relating space used by sql table. below is script to find out space usedby Table [EC_cart].

sp_spaceused [EC_cart]


Thursday, May 14, 2009

Creating Comm Separated string Using Select Statement.

We can Create comma separated string in Sql using simple select statement.

here is the sql script for this task.

declare @AllUsers varchar(500)
set @AllUsers=''
Select @AllUsers=@AllUsers+cast([ID] as varchar(20))+',' from User_mst
print substring(@AllUsers,0,len(@AllUsers))


Get Remote Client's IP Address and UserName.

In we can get IP Address of WebClient using Request object.and If User is Loggen in With Some Authentication like Forms,Windows or any other. we can also track detail of User Loggen in User on that Web Site.

string strIpAddress = string.Empty;
strIpAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (strIpAddress == null)
strIpAddress = Request.ServerVariables["REMOTE_ADDR"];

In above Code strIpAddress will Contain IP of Client machine..
this will not show up real IP if your Client is Behind LAN firewalls.


the code in above line will returns UserName . If User is Loggen in..


HashSet New Collection Added in C# 3.5

In C# 3.5 there is new collection datataype added named HashSet.HashSet is designed to suppost mathamatical Calculations like Union, Intersection, IsSubsetOf, IsSupersetOf.
Hashable Conains Unique values.

HashSet hst = new HashSet();


above example will Print count=3. because HashSe Contains Only three unique elements.

HashSet is Faster than IList in many ways.

To knwo more feature of HashSe Visit..


Create PDF from Text input in C# using iTextSharp.dll

We can Create PDF file from text data using many third party dlls.
iTextSharp is one of them Which provide many function to manipulate this type of stuff.
you have to add referance of iTextSharp.dll to your project. and add iTextSharp.text.pdf , iTextSharp.text in page directive.

public partial class CreatePDF : System.Web.UI.Page
protected override void OnInit(EventArgs e)
btnCreate.Click += new EventHandler(btnCreate_Click);
protected void Page_Load(object sender, EventArgs e)
Response.Write("Enter data and click to create pdf....");
public void btnCreate_Click(object sender, EventArgs e)
string iCreatePDFdir = Server.MapPath("~/") + "iCreatePDF\\PDFTest";
string iCreatePDFTest = iCreatePDFdir + "\\PDFTest.pdf";
Document pdfDocCreatePDF = new Document();
PdfWriter.GetInstance(pdfDocCreatePDF, new FileStream(iCreatePDFTest, FileMode.Create));
pdfDocCreatePDF.Add(new Paragraph(txtContent.Text));

This the demo code for that.


Bind HashTable Data with Dropdownlist.

We can bind hashtanle with dropdownlist same way as datatable and dataset.
you have to remember that how to set DataTextField and DataValueFiled Properties
of dropdownlist.

this is the code to bind HashTable with dropdownlist in

DropDownList ddl1 = new DropDownList();
System.Collections.Hashtable hsTable = new Hashtable();
hsTable.Add("0", "India");
hsTable.Add("1", "USA");
ddl1.DataSource = hsTable;
ddl1.DataTextField = "Value";
ddl1.DataValueField = "Key";


Tuesday, May 12, 2009

Insert Multiple Values in Database Simultaneously.

How to utilize table valued parameter in SQl server 2008.

we can use tablevalued Parameter feature of SQl server to pass multiple values into sql server. we can insert multiple values in database Using Sql server 2008 User Define types. In Sql server 2008 we can pass Datatabel as parameter in Sqlcommand. in backend that parameter will be declared as type of that User Define Type.

(1)this is the SQL Script for Creating User Define Type.

CREATE Type TypeNameas Table(ID int,Name varchar(20))

(2)Procedure Showing How to Utilize input table.

CREATE procedure haresh_InsertUser( @InputTable as PrameterTable readonly)asBEGINinsert into Users_mst (Name)
select [Name] from @InputTable

you can also update multiple values in database using syntex ..

update Users_mst set Name=T.Name from
SELECT ID,[Name] FRom @InputTable
) AS T
WHERE T.ID= Users_mst.ID

(3)How to pass table from C# to SQl.

SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = Conn;
cmd.CommandText = "haresh_InsertUser";
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Rows.Add(1, "Haresh");
dt.Rows.Add(2, "Kinjal");
cmd.Parameters.Add(new SqlParameter("@InputTable", dt)); Response.Write(cmd.ExecuteNonQuery());


Saturday, May 9, 2009

Give Rownumber to rows in select statements.

This is the syntax to select rows with IndexNumber in Select Operator.

we can use built in ROW_NUMBER function to achive this.

Select ROW_NUMBER() over (order by ID) as IndexNo,* from EC_OrderDetail


Tuesday, May 5, 2009

Perform Join with table valued function in SQL server 2005

Using APPLY operator we can efficiently perform join operation with table returned by SQL able valued function. APPLY is new in sql server 2005.

It allows you to call a function-returning TABLE(Table Valued function) for each row of your outer TABLE. We can pass outer table's columns as function arguments.

We can have two types of APPLY Operations.


this is much like Inner join .that means it will not return the outer tables row if function table have no row corresponding to it.


this is much like Outerjoin .that means it will returns a NULL values if function table have no row corresponding to it.

My [Order] table have ID,CustomerID and OrderDate Fields.
My [OrderDetail] have ID,OrderID and ItemCount Fields.

Here is the Table valued function.

CREATE Function GetOrderDetailByOrderID(@OrderID int) returns tablereturn( select * from EC_OrderDetail where OrderID=@OrderID)

Below SQL Script With CROSS Apply.

Select * from EC_Order [ordertab] CROSS APPLYGetOrderDetailByOrderID(ordertab.ID) as OrderDetailorder by OrderDetail.OrderID

returns same result as Below SQL Script With Inner join

Select * from EC_Order [ordertab] inner joinEC_OrderDetail detail on(detail.orderId=ordertab.ID)order by detail.orderId

Follow this ( ) as referance.


Monday, May 4, 2009

how to sum time Value in Sql server.

In sql server we can't sumup time Using sum function. we have to make some stuff for summing up time value in sql server. we can do this by replacing ":" from time by "." and then treating time as Float. then sumup hours and minute individualy and then.after Convert munites to hour and add them to calculated hour..

this is tabel whose time column need to be sumup..

this is the result..

ans this is the sql script.

declare @tmpTable Table(AH varchar(20))
insert into @tmpTable values('7:30')
insert into @tmpTable values('2:30')
select * from @tmpTable
declare @Minutes as float
declare @Hours as float
declare @HoursFromMunite as Float
select @Hours=sum(cast (substring(AH,0,CHARINDEX(':',AH)) as int)),@Minutes= sum(cast( substring(AH,CHARINDEX(':',AH)+1,len(AH)) as int)) from @tmpTable
set @HoursFromMunite=Floor(@Minutes/60)
set @Hours=@Hours+@HoursFromMunite
set @Minutes= ((@Minutes/60)-@HoursFromMunite)*60
select cast(@Hours as varchar(5))+':'+cast(@Minutes as varchar(5)) as Total


Convert column as row in sql server using PIVOT function.

when we developing resporting application with sql server sometime need to convert column as row in SQL server. we can use PIVOT function of sql server to do this.
I have sum of Sold items in table this.

i want it as this.

this transposition can be achived by below SQL Script.

select EC_Items.ItemName, sum(ItemCount) ItemCount from EC_OrderDetail inner join EC_Items on(EC_Items.ID=EC_OrderDetail.ItemID)
Group by ItemID,EC_Items.ItemName
order by ItemID
declare @Columns varchar(4000)
set @Columns = (Select distinct [ItemName] from EC_OrderDetail inner join EC_Items on(EC_Items.ID=EC_OrderDetail.ItemID)for XML path(''))
set @Columns=replace(@Columns,'','[')
set @Columns=replace(@Columns,'
set @Columns=substring(@Columns,0,len(@Columns))
print @Columns
declare @Query nvarchar(4000)
set @Query=
from ( select [ItemName],ItemCount from EC_OrderDetail inner join EC_Items on(EC_Items.ID=EC_OrderDetail.ItemID)) as SourceTable
pivot( sum(ItemCount) for [ItemName] in (
'+@Columns+')) as pivoteTable;'
declare @Parameters as nvarchar(4000)
set @Parameters='@Columns varchar(4000)'
exec sp_executesql @Query,@Parameters,@Columns=@Columns


Saturday, May 2, 2009

Displaye Dates on which particular day Falles Between two dates.

If we want that between two dates on which dates particular day(Monday,tuesday) falls.
we can write Code both in C# and Sql server.
between two dates..LeftDate='2009-04-02' and RightDate='2009-04-02'
Monday Falls On dates. 2009-04-05 , 2009-04-12 , 2009-04-19 .

To find out this we will..

Insert date range in some table.perform looping on table rows then looping between dates.
and insert Date on which monday falls in New table. than select distinct among that table.

(1)Code In c#.

protected void Page_Load(object sender, EventArgs e)
Gridview1.DataSource = GetDatatable();
DataTable dt = GetDatatable();
DataTable dtNew = new DataTable();
dtNew.Columns.Add("MondayDates", typeof(DateTime));
dt.Columns.Add("MondayDates", typeof(DateTime));
foreach (DataRow dr in dt.Rows)
DateTime dt1 = Convert.ToDateTime(dr["Leftdates"]);
DateTime dt2 = Convert.ToDateTime(dr["Rightdates"]);
while (dt1 <= dt2) { if (dt1.DayOfWeek == DayOfWeek.Monday) { dtNew.Rows.Add(dt1); } dt1 = dt1.AddDays(1); } } Gridview1.DataSource = dtNew.DefaultView.ToTable("DistinctTable", true, "MondayDates"); Gridview1.DataBind(); } private DataTable GetDatatable() { DataTable dt = new DataTable(); dt.Columns.Add("Leftdates", typeof(DateTime)); dt.Columns.Add("Rightdates", typeof(DateTime)); dt.Rows.Add("4/1/2009", "4/28/2009"); return dt; }

(2)Code in SQL server.

Using Cusror in Sql server we can perform looping in sql server.

declare @tmpTable TABLE(LeftDates datetime,RightDates datetime)
declare @mondayTable TABLE(MondayDate datetime)
insert into @tmpTable values('2009-04-02','2009-04-20')
insert into @tmpTable values('2009-04-02','2009-04-20')
--Select * from @tmpTable
Declare myCursor Cursor for Select LeftDates,RightDates from @tmpTable
open myCursor
declare @LeftDate as Datetime
declare @RightDate as Datetime
declare @dateDay int
fetch next from myCursor Into @LeftDate,@RightDate
fetch next from myCursor Into @LeftDate,@RightDate
declare @tmpLeftDate datetime
set @tmpLeftDate=@LeftDate
WHILE @tmpLeftDate < @RightDate BEGIN SET @tmpLeftDate = @tmpLeftDate + 1 select @dateDay=DATEPART(w,@tmpLeftDate) if(@dateDay=1)--Day Number of Monday =1 insert into @mondayTable values(@tmpLeftDate) END end close myCursor deallocate myCursor select distinct MondayDate from @mondayTable

thats all.


Friday, May 1, 2009

Select Distinct Rows from DataTable Without Linq.

We can select distinct rows from datatable by creating DataView. DataView Have different methods for sorting,searching etc. operations on datarows. DataView have a Method Called ToTable() which Creates and returns a new Datatable based on rows in an existing datatable.
Usind this method we can select distinct rows based on particular Column.. here is the code.

Gridview1.DataSource = dtNew.DefaultView.ToTable( true, "MondayDates"); Gridview1.DataBind();

dtNew Is Datatable which contains duplicate rows MondayDates column.
but it will binds only Distinct rows to Grid..
parameter true Specify that need to select distinct rows from table.
parameter MondayDates is the name of column on which distinct clouse should be applied.

Thats all.
Hope this will help you


Dynamically change css for DOM element.

Using jQuery we can change css attribute dynamically.

(1)Find by class and set Css attribute.


(2)Find by class and Remove class.


similar methods are addClass, toggleClass

using jQuery we can make javascript programming easier.


Call Webservice from javascript.

How to call webservice from javascript.

In we can develope webservices.we can call webservice in our application by adding webreferance to that webservice.In 3.5 We can also call webservice using javascript. 3.5 also resurns JSON in response to call of webservice.this is possible using namespance System.Web.Script.Services. this namespace has a class called ScriptService.using this class we can call webservice using javascript.

(1)this is WebService.Cs of My webservice.

using System.Web.Services;
using System.Web.Script.Services;
namespace MyService
public class User
public int ID;
public string Name;
[WebService(Namespace = "")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class WebService : System.Web.Services.WebService
public WebService()
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public User HelloWorld(string Name)
User u = new User();
u.ID = 1;
u.Name = Name;
return u;

(2)Add ScriptManager to your aspx page.
(3)Give referance to webservice in ScriptManager
(4)Give referance to script which will handle response of webservice in ScriptManager

<asp:ScriptManager ID="ScriptManager2" runat="server">
<asp:ServiceReference Path="~/WebService.asmx" />
<asp:ScriptReference Path="~/WebService.asmx.js" />

(5)add this javascript in WebService.asmx.js

var HelloWorldResult="";
function HelloWorld(name)
function HelloWorldSuccess(response)
function HelloWorldFailure(error)

(6)Call Helloworld Function in Your aspx Page.

HelloWorld("Haresh!!!Thi is Call From javascript");

Hope this will help you.


Displaying last modified date of page.

Using System.IO Name space we can find out time when page was last modified. we can also display LastWriteTime,CreationTime etc. of page. here if the code to display LastAccssTime of page.

string filePath = Server.MapPath(Request.Path);
System.IO.FileInfo fInfo = new System.IO.FileInfo(filePath);
lblLastWriteTime.Text = fInfo.CreationTime.ToString();

Put this code in Page_Load event of your page.