Monday, May 25, 2009

How to enable or disable LinkButton in Javascript.

we can make asp.net 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"
OnClick="lnkTest_Click">Test</asp:LinkButton>


(2)Style for enabling and Disabling is

<style>
.LnkEnabled
{
cursor: pointer;
}
.LnkDisabled
{
cursor: default;
color: Gray;
}
</style>


(3) and javascript fiuction is

<script language="javascript">
function EnableLinkButton(ID,flag)
{
document.getElementById(ID).onclick=function(){return flag;};
if(!flag)
{
document.getElementById(ID).setAttribute("disabled","disabled");
document.getElementById(ID).className="LnkDisabled";
}
else
{
document.getElementById(ID).setAttribute("disabled","");
document.getElementById(ID).className="LnkEnabled";
}
}
EnableLinkButton('<%= lnkTest.ClientID %>',false);
</script>


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

Thanks.

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">
FloatElement();
window.onscroll=FloatElement;
window.onresize=FloatElement;
function FloatElement()
{
var myfloaingTop=500;
if(document.all)
{
document.getElementById("myfloaing").style.top=document.documentElement.scrollTop+myfloaingTop;
}
else
{
document.getElementById("myfloaing").style.top=window.pageYOffset+myfloaingTop+'px';
}
}
</script&ght;


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.
</div>


thanks.

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;
#endregion
#region Properties
public int GetAverage
{
get
{
return Average;
}
set
{
Average = value;
}
}
#endregion
}
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();
}
#endregion
}



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" };
Response.Write("<br/>");
Response.Write("<b>ToXml</b>");
Response.Write("<br/>");
Response.Write("<br/>");
Response.Write(Server.HtmlEncode(Honda.ToXml()));
Response.Write("<br/>");
Response.Write("<br/>");
Response.Write("<b>SerilizeToXml</b>");
Response.Write("<br/>");
Response.Write("<br/>");
Response.Write(Server.HtmlEncode(Honda.SerilizeToXml()));
}


Thanks.

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.


(1)Enum.GetName
(2)Eum.GetValues

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";
ddlDevices.DataBind();



Thanks.

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]

Thanks.

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))

Thanks.

Get Remote Client's IP Address and UserName.

In asp.net 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.

Request.ServerVariables["REMOTE_USER"]

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

Thanks.

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.
eg.

HashSet hst = new HashSet();
hst.Add(1);
hst.Add(2);
hst.Add(2);
hst.Add(2);
hst.Add(2);
hst.Add(3);


Response.Write("count="+Count);

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..

http://www.vcskicks.com/hashset.php
and
http://msdn.microsoft.com/en-us/library/bb495294.aspx

Thanks.

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)
{
base.OnInit(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";
Directory.CreateDirectory(iCreatePDFdir);
Document pdfDocCreatePDF = new Document();
PdfWriter.GetInstance(pdfDocCreatePDF, new FileStream(iCreatePDFTest, FileMode.Create));
pdfDocCreatePDF.Open();
pdfDocCreatePDF.Add(new Paragraph(txtContent.Text));
pdfDocCreatePDF.Close();
Response.Redirect("~/iCreatePDF/PDFTest/PDFTest.pdf");
}
}


This the demo code for that.

Thanks.

Bind HashTable Data with Dropdownlist.

We can bind hashtanle with asp.net 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 asp.net..

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";
ddl1.DataBind();
form1.Controls.Add(ddl1);


Thanks.

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
END


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());

Thanks.

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

thanks.

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.

(1)CROSS APPLY.

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.

(2)OUTER APPLY.

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

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 (http://www.codeproject.com/KB/database/APPLY_Operator.aspx ) as referance.

Thanks.

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
if(@HoursFromMunite>0)
set @Minutes= ((@Minutes/60)-@HoursFromMunite)*60
select cast(@Hours as varchar(5))+':'+cast(@Minutes as varchar(5)) as Total


Thanks.

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 column.like this.













i want it as row.like 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=
'select
'+@Columns+'
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




Thanks.

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.
eg.
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();
Gridview1.DataBind();
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
while(@@fetch_status=0)
begin
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.

thanks.

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

Thanks

Dynamically change css for DOM element.

Using jQuery we can change css attribute dynamically.


(1)Find by class and set Css attribute.

$(".overlay").css({'display':'block','background-color':'red'});

(2)Find by class and Remove class.

$(".overlay").removeClass("overlay");

similar methods are addClass, toggleClass

using jQuery we can make javascript programming easier.

Thanks.

Call asp.net Webservice from javascript.

How to call asp.net webservice from javascript.

In asp.net we can develope webservices.we can call webservice in our application by adding webreferance to that webservice.In asp.net 3.5 We can also call webservice using javascript. asp.net 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 asp.net 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 = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class WebService : System.Web.Services.WebService
{
public WebService()
{
}
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
[WebMethod]
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">
<Services>
<asp:ServiceReference Path="~/WebService.asmx" />
</Services>
<Scripts>
<asp:ScriptReference Path="~/WebService.asmx.js" />
</Scripts>
</asp:ScriptManager&



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


var HelloWorldResult="";
function HelloWorld(name)
{
MyService.WebService.HelloWorld(name,HelloWorldSuccess,HelloWorldFailure,null);
}
function HelloWorldSuccess(response)
{
alert(response.Name);
}
function HelloWorldFailure(error)
{
alert(error);
}



(6)Call Helloworld Function in Your aspx Page.

<script>
HelloWorld("Haresh!!!Thi is Call From javascript");
</script>


Hope this will help you.

Thanks.

Displaying last modified date of asp.net page.

Using System.IO Name space we can find out time when page was last modified. we can also display LastWriteTime,CreationTime etc. of asp.net page. here if the code to display LastAccssTime of asp.net 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.

Thanks.