Search content within the blog

Tuesday, June 30, 2009

Javascript function to find client time

The Date object is useful when you want to display a date or use a timestamp in some sort of calculation. In Java, you can either make a Date object by supplying the date of your choice, or you can let JavaScript create a Date object based on your visitor's system clock. It is usually best to let JavaScript simply use the system clock.

When creating a Date object based on the computer's (not web server's!) internal clock, it is important to note that if someone's clock is off by a few hours or they are in a different time zone, then the Date object will create a different times from the one created on your own computer.

JavaScript Date Today (Current)
To warm up our JavaScript Date object skills, let's do something easy. If you do not supply any arguments to the Date constructor (this makes the Date object) then it will create a Date object based on the visitor's internal clock.
HTML & JavaScript Code:
<h4>It is now
<script type="text/javascript">
<!--
var currentTime = new Date()
//-->
</script>
</h4>
Display:
It is now
Nothing shows up! That's because we still don't know the methods of the Date object that let us get the information we need (i.e. Day, Month, Hour, etc).
Get the JavaScript Time
The Date object has been created, and now we have a variable that holds the current date! To get the information we need to print out, we have to utilize some or all of the following functions:
• getTime() - Number of milliseconds since 1/1/1970 @ 12:00 AM
• getSeconds() - Number of seconds (0-59)
• getMinutes() - Number of minutes (0-59)
• getHours() - Number of hours (0-23)
• getDay() - Day of the week(0-6). 0 = Sunday, ... , 6 = Saturday
• getDate() - Day of the month (0-31)
• getMonth() - Number of month (0-11)
• getFullYear() - The four digit year (1970-9999)
Now we can print out the date information. We will be using the getDate, getMonth, and getFullYear methods in this example.
HTML & JavaScript Code:
<h4>It is now
<script type="text/javascript">
<!--
var currentTime = new Date()
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var year = currentTime.getFullYear()
document.write(month + "/" + day + "/" + year)
//-->
</script>
</h4>

Display:
It is now 6/30/2009 !
Notice that we added 1 to the month variable to correct the problem with January being 0 and December being 11. After adding 1, January will be 1, and December will be 12.
JavaScript Current Time Clock
Now, instead of displaying the date we, will display the format you might see on a typical digital clock -- HH:MM AM/PM (H = Hour, M = Minute).
HTML & JavaScript Code:
<h4>It is now
<script type="text/javascript">
<!--
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
if (minutes < 10){
minutes = "0" + minutes
}
document.write(hours + ":" + minutes + " ")
if(hours > 11){
document.write("PM")
} else {
document.write("AM")
}
//-->
</script>
</h4>

Display:
It is now 14:46 PM
Above, we check to see if either the hours or minutes variable is less than 10. If it is, then we need to add a zero to the beginning of minutes. This is not necessary, but if it is 1:01 AM, our clock would output "1:1 AM", which doesn't look very nice at all!

Thursday, June 25, 2009

Difference between Ref and Out Parameter

Ref and out parameter passing modes are used to allow a method to alter variables passed in by the caller. The difference between ref and out is subtle but important. Each parameter passing mode is designed to apply to a slightly different programming scenario. The important difference between out and ref parameters is the definite assignment rules used by each.

The caller of a method which takes an out parameter is not required to assign to the variable passed as the out parameter prior to the call; however, the callee is required to assign to the out parameter before returning.

Here's a simple example:

class OutExample
{
// Splits a string containing a first and last name separated
// by a space into two distinct strings, one containing the first name and one containing the last name

static void SplitName(string fullName, out string firstName, out string lastName)
{
// NOTE: firstName and lastName have not been assigned to yet. Their values cannot be used.
int spaceIndex = fullName.IndexOf(' ');
firstName = fullName.Substring(0, spaceIndex).Trim();
lastName = fullName.Substring(spaceIndex).Trim();
}

static void Main()
{
string fullName = "Yuan Sha";
string firstName;
string lastName;

// NOTE: firstName and lastName have not been assigned yet. Their values may not be used.
SplitName(fullName, out firstName, out lastName);
// NOTE: firstName and lastName have been assigned, because the out parameter passing mode guarantees it.

System.Console.WriteLine("First Name '{0}'. Last Name '{1}'", firstName, lastName);
}
}

One way to think of out parameters is that they are like additional return values of a method. They are very convenient when a method returns more than one value, in this example firstName and lastName. Out parameters can be abused however. As a matter of good programming style if you find yourself writing a method with many out parameters then you should think about refactoring your code. One possible solution is to package all the return values into a single struct.

In contrast ref parameters are considered initially assigned by the callee. As such, the callee is not required to assign to the ref parameter before use. Ref parameters are passed both into and out of a method.

Here's an example:

class RefExample
{
static object FindNext(object value, object[] data, ref int index)
{
// NOTE: index can be used here because it is a ref parameter
while (index < data.Length)
{
if (data[index].Equals(value))
{
return data[index];
}
index += 1;
}
return null;
}

static void Main()
{
object[] data = new object[] {1,2,3,4,2,3,4,5,3};

int index = 0;
// NOTE: must assign to index before passing it as a ref parameter
while (FindNext(3, data, ref index) != null)
{
// NOTE: that FindNext may have modified the value of index
System.Console.WriteLine("Found at index {0}", index);
index += 1;
}

System.Console.WriteLine("Done Find");
}
}

The two parameter passing modes addressed by out and ref are subtly different, however they are both very common. The subtle difference between these modes leads to some very common programming errors. These include:

* not assigning a value to an out parameter in all control flow paths
* not assigning a value to variable which is used as a ref parameter

Because the C# language assigns different definite assignment rules to these different parameter passing modes, these common coding errors are caught by the compiler as being incorrect C# code.

The crux of the decision to include both ref and out parameter passing modes was that allowing the compiler to detect these common coding errors was worth the additional complexity of having both ref and out parameter passing modes in the language.

Thursday, June 4, 2009

Use of Coalesce function in SQL Server

The basic syntax of the coalesce function is a s follows...

select ( exp1, exp2,,,expn)as someresult from table

The function selects the first not null value of the expressions specified.

say you have a table called employee and his salary based on his job type can be inserted in either of the 3 columns stored ina table in sqlserver . Say the columns are col1, col2, col3....so st select his/her salary the statement with the help of coalesce would be as follows...
select coalesce(col1,col2,col3)* 5 as salary from dbo.tblSalary

An example shall make it more clear...

Create the following table in your database
/****** Object: Table [dbo].[tbCoalesce] Script Date: 06/04/2009 20:33:54 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[tbCoalesce](
[col1] [int] NULL,
[col2] [int] NULL,
[col3] [int] NULL
) ON [PRIMARY]

GO


Also insert values using these statements...
insert into dbo.tbCoalesce (col1,col2,col3)
select null, null, 1 union
select null, 2, null union
select null, null, 3

paste the following query in quey analzer to see the output shown below

select coalesce(col1,col2,col3)* 5 as salary from
dbo.tbCoalesce

Salary
   5
   15
   10

You can also use it to pivot the resultset....

Using Coalesce to Pivot

If you run the following statement against the AdventureWorks database
SELECT Name
FROM HumanResources.Department
WHERE (GroupName = 'Executive General and Administration')


you will come up with a standard result set such as this.





If you want to pivot the data you could run the following command.
DECLARE @DepartmentName VARCHAR(1000)

SELECT @DepartmentName = COALESCE(@DepartmentName,'') + Name + ';'
FROM HumanResources.Department
WHERE (GroupName = 'Executive General and Administration')
SELECT @DepartmentName AS DepartmentNames


and get the following result set.

Wednesday, June 3, 2009

Check and uncheck All checkboxes in gridview including header checkbox

This is a common requirement in every project that is if a header checkbox is selected in the gridview its child checkboxes also should get selected and if any child checkbox is unchecked the header checkbox should get unchecked automatically.

Note:

* Just Copy Paste the code as it is in respective pages.
* The code is self Explainable.
* Run the page and work on the check boxes.

ASPX PAGE

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="DataboundControls._Default" %>

<!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>
<script type="text/javascript">
function SelectAll(id)
{
//get reference of GridView control
var grid = document.getElementById("<%= FileList.ClientID %>");
//variable to contain the cell of the grid
var cell;

if (grid.rows.length > 0)
{
//loop starts from 1. rows[0] points to the header.
for (i=1; i<grid.rows.length; i++)
{
//get the reference of first column
cell = grid.rows[i].cells[0];

//loop according to the number of childNodes in the cell
for (j=0; j<cell.childNodes.length; j++)
{
//if childNode type is CheckBox
if (cell.childNodes[j].type =="checkbox")
{
//assign the status of the Select All checkbox to the cell checkbox within the grid
cell.childNodes[j].checked = document.getElementById(id).checked;
}
}
}
}
}

function CheckAndUncheckHeaderBox(HeaderlevelCheckBox)
{
//get reference of GridView control
var grid = document.getElementById("<%= FileList.ClientID %>");
//variable to contain the cell of the grid
var cell;

if (grid.rows.length > 0)
{
var Totallength=grid.rows.length;
var CheckedBoxesCounter=0;
//loop starts from 1. rows[0] points to the header.
for (i=1; i<grid.rows.length; i++)
{
//get the reference of first column
cell = grid.rows[i].cells[0];

//loop according to the number of childNodes in the cell
for (j=0; j<cell.childNodes.length; j++)
{
//if childNode type is CheckBox
if (cell.childNodes[j].type =="checkbox" && cell.childNodes[j].checked==true)
{
CheckedBoxesCounter=CheckedBoxesCounter+1;
}
}
}
alert(CheckedBoxesCounter);
alert(Totallength);
if(CheckedBoxesCounter+1==Totallength)
{

alert(true);
document.getElementById(HeaderlevelCheckBox).checked=true;
alert("done");
}
else
{
alert(false);
document.getElementById(HeaderlevelCheckBox).checked=false;
alert("done");
}
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<div>
<h1>
Check/Uncheck All CheckBoxes in a GridView Using Client-Side Script</h1>
<p>
<asp:Label ID="Summary" runat="server" EnableViewState="False" Font-Bold="False"
Font-Italic="False" Font-Size="XX-Large" ForeColor="Red"></asp:Label> </p>
<p>
<asp:GridView ID="FileList" runat="server" CellPadding="4"
ForeColor="#333333" GridLines="None" AutoGenerateColumns="False" DataKeyNames="FullName" AllowPaging="false" OnRowDataBound="FileList_RowDataBound">
<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
<PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox runat="server" ID="HeaderLevelCheckBox" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox runat="server" ID="RowLevelCheckBox" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="CreationTime" HeaderText="Created On">
<ItemStyle HorizontalAlign="Right" />
</asp:BoundField>
<asp:BoundField DataField="Length" DataFormatString="{0:N0}" HeaderText="File Size"
HtmlEncode="False">
<ItemStyle HorizontalAlign="Right" />
</asp:BoundField>
</Columns>
</asp:GridView>
<asp:HiddenField runat="server" ID="hdnCheckBoxheader" />
</p>
<p>
<asp:Button runat="server" ID="DeleteButton" Text="Delete Checked Files" />
(<i>go ahead and click this... it won't really delete the files</i>)
</p>
<p>
<asp:Literal ID="CheckBoxIDsArray" runat="server"></asp:Literal> </p>
</div>
</div>
</form>
</body>
</html>


ASPX.CS PAGE

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.IO;
using System.Collections.Generic;
namespace DataboundControls
{
public partial class _Default : System.Web.UI.Page
{

protected void Page_Load(object sender, EventArgs e)
{
string PhysicalPath = Request.PhysicalApplicationPath;
DirectoryInfo objDirectory = new DirectoryInfo(PhysicalPath);
FileList.DataSource = objDirectory.GetFiles();
FileList.DataBind();

foreach (GridViewRow gvr in FileList.Rows) {
//Get a programmatic reference to the CheckBox control
CheckBox cb = (CheckBox)gvr.FindControl("RowLevelCheckBox");
ClientScript.RegisterArrayDeclaration("CheckBoxIDs", string.Concat("'", cb.ClientID, "'"));
}
}

protected void FileList_RowDataBound(object Sender, GridViewRowEventArgs e)
{

if (e.Row.RowType == DataControlRowType.Header)
{
hdnCheckBoxheader.Value = ((CheckBox)e.Row.FindControl("HeaderLevelCheckBox")).ClientID.ToString();
((CheckBox)e.Row.FindControl("HeaderLevelCheckBox")).Attributes.Add("onclick", "Javascript:SelectAll('" + ((CheckBox)e.Row.FindControl("HeaderLevelCheckBox")).ClientID + "')");
}

if (e.Row.RowType == DataControlRowType.DataRow)
{
CheckBox RowLevelCheckBox = (CheckBox)e.Row.FindControl("RowLevelCheckBox");
RowLevelCheckBox.Attributes.Add("onclick", "Javascript:CheckAndUncheckHeaderBox('" + hdnCheckBoxheader.Value + "')");

}
}
}
}

Generate a HASH value using SQL Server 2005/2008

Do you want to pass a string and generate a HASH value from it using SQL Server? Here’s a very simple way of doing so using HashBytes. Let us see this with an example:

DECLARE @SomeValue nvarchar(50);
SELECT @SomeValue = 'SQLServerCurry';
SELECT HashBytes('SHA1', @SomeValue);
GO



generates an output

0x51FD96B1BD5CE0003370551D5498BA3C0E64BE4C

Using HashBytes, you can use algorithms like MD2, MD4, MD5, SHA or SHA1. The input string can be a varchar, nvarchar or varbinary and can be upto a maximum of 8000 bytes