Monday, December 7, 2009

DBCC CHECKIDENT ('table_name', RESEED, new_reseed_value)

The current identity value is set to the new_reseed_value. If no rows have been inserted to the table since it was created, the first row inserted after executing DBCC CHECKIDENT will use new_reseed_value as the identity. Otherwise, the next row inserted will use new_reseed_value + 1. If the value of new_reseed_value is less than the maximum value in the identity column, error message 2627 will be generated on subsequent references to the table.

1. Consider our table having some row. Now we are deleting the table with query

DELETE FROM table_name

DBCC CHECKIDENT ('table_name', RESEED, 0)
The table will generate an identity value form 1 and not from 0.


2. Now we are truncating the table with TRUNCATE TABLE Statement.

TRUNCATE TABLE table_name

DBCC CHECKIDENT ('table_name', RESEED, 0)
The table will generate an identity value form 0.

During INSERT if there is an error, the row will not Inserted but the Identity value increased according to(IDENT_INCR) the Increment.

Wednesday, December 2, 2009

Methods to find table INDEX or Statistics age for better performance

Original Post

 
SELECT OBJECT_NAME(tbl.object_id),
'Index Name' = ind.name ,
'Statistics Date' = STATS_DATE(ind.object_id, ind.index_id)
FROM SYS.INDEXES ind
INNER JOIN SYS.TABLES tbl
ON tbl.OBJECT_ID = ind.object_id
WHERE tbl.TYPE = 'U'

--USE babu;
--GO
--EXEC sp_updatestats --To update all STATISTICS in the DB

Create Parameters

DECLARE @TABLE_NAME VARCHAR(50) = 'PrameterTable'
DECLARE @TableName AS         VARCHAR(200)
DECLARE @ParamNames AS        VARCHAR(8000)
SET @TableName = 'TableTest'
SELECT @ParamNames = (COALESCE(@ParamNames + CHAR(13) + CHAR(10), '') +
       CASE
              WHEN DATA_TYPE = 'bigint'
              THEN '@' + COLUMN_NAME + ' ' + DATA_TYPE
              WHEN DATA_TYPE = 'binary'
              THEN '@' + COLUMN_NAME + ' ' + DATA_TYPE + '(' + CAST(character_maximum_length AS VARCHAR) + ')'
              WHEN DATA_TYPE = 'Bit'
              THEN '@' + COLUMN_NAME + ' ' + DATA_TYPE
              WHEN DATA_TYPE = 'Char'
              THEN '@' + COLUMN_NAME + ' ' + DATA_TYPE + '(' + CAST(character_maximum_length AS VARCHAR) + ')'
              WHEN DATA_TYPE = 'Date'
              THEN '@' + COLUMN_NAME + ' ' + DATA_TYPE
              WHEN DATA_TYPE = 'DateTime'
              THEN '@' + COLUMN_NAME + ' ' + DATA_TYPE
              WHEN DATA_TYPE = 'DateTime2'
              THEN '@' + COLUMN_NAME + ' ' + DATA_TYPE
              WHEN DATA_TYPE = 'DateTimeOffset'
              THEN '@' + COLUMN_NAME + ' ' + DATA_TYPE
              WHEN DATA_TYPE = 'Decimal'
              THEN '@' + COLUMN_NAME + ' ' + DATA_TYPE + '(' + CAST(NUMERIC_precision AS VARCHAR) + ',' + CAST(numeric_scale AS VARCHAR) + ')'
              WHEN DATA_TYPE = 'float'
              THEN '@' + COLUMN_NAME + ' ' + DATA_TYPE + '(' + CAST(NUMERIC_precision AS VARCHAR) + ')'
              WHEN DATA_TYPE = 'geography'
              THEN '@' + COLUMN_NAME + ' ' + DATA_TYPE
              WHEN DATA_TYPE = 'geometry'
              THEN '@' + COLUMN_NAME + ' ' + DATA_TYPE
              WHEN DATA_TYPE = 'hierarchyid'
              THEN '@' + COLUMN_NAME + ' ' + DATA_TYPE
              WHEN DATA_TYPE = 'image'
              THEN '@' + COLUMN_NAME + ' ' + DATA_TYPE
              WHEN DATA_TYPE = 'int'
              THEN '@' + COLUMN_NAME + ' ' + DATA_TYPE --+ '(' + CAST(NUMERIC_precision AS VARCHAR) + ')'
              WHEN DATA_TYPE = 'money'
              THEN '@' + COLUMN_NAME + ' ' + DATA_TYPE --+ '(' + CAST(NUMERIC_precision AS VARCHAR) + ',' + CAST(numeric_scale AS VARCHAR) + ')'
              WHEN DATA_TYPE = 'NCHAR'
              THEN '@' + COLUMN_NAME + ' ' + DATA_TYPE + '(' + CAST(character_maximum_length AS VARCHAR) + ')'
              WHEN DATA_TYPE = 'numeric'
              THEN '@' + COLUMN_NAME + ' ' + DATA_TYPE + '(' + CAST(NUMERIC_precision AS VARCHAR) + ',' + CAST(numeric_scale AS VARCHAR) + ')'
              WHEN DATA_TYPE = 'NVARCHAR'
              THEN '@' + COLUMN_NAME + ' ' + DATA_TYPE + '(' + CAST(character_maximum_length AS VARCHAR) + ')'
              WHEN DATA_TYPE = 'ntext'
              THEN '@' + COLUMN_NAME + ' ' + DATA_TYPE --+ '(' + CAST(character_maximum_length AS VARCHAR) + ')'
              WHEN DATA_TYPE = 'REAL'
              THEN '@' + COLUMN_NAME + ' ' + DATA_TYPE --+ '(' + CAST(NUMERIC_precision AS VARCHAR) + ')'
              WHEN DATA_TYPE = 'smalldatetime'
              THEN '@' + COLUMN_NAME + ' ' + DATA_TYPE
              WHEN DATA_TYPE = 'smallint'
              THEN '@' + COLUMN_NAME + ' ' + DATA_TYPE --+ '(' + CAST(NUMERIC_precision AS VARCHAR) + ')'
              WHEN DATA_TYPE = 'smallmoney'
              THEN '@' + COLUMN_NAME + ' ' + DATA_TYPE --+ '(' + CAST(NUMERIC_precision AS VARCHAR) + ',' + CAST(numeric_scale AS VARCHAR) + ')'
              WHEN DATA_TYPE = 'sql_variant'
              THEN '@' + COLUMN_NAME + ' ' + DATA_TYPE
              WHEN DATA_TYPE = 'text'
              THEN '@' + COLUMN_NAME + ' ' + DATA_TYPE + '(' + CAST(character_maximum_length AS VARCHAR) + ')'
              WHEN DATA_TYPE = 'time'
              THEN '@' + COLUMN_NAME + ' ' + DATA_TYPE
              WHEN DATA_TYPE = 'timestamp'
              THEN '@' + COLUMN_NAME + ' ' + DATA_TYPE
              WHEN DATA_TYPE = 'tinyint'
              THEN '@' + COLUMN_NAME + ' ' + DATA_TYPE + '(' + CAST(NUMERIC_precision AS VARCHAR) + ')'
              WHEN DATA_TYPE = 'uniqueidentifier'
              THEN '@' + COLUMN_NAME + ' ' + DATA_TYPE
              WHEN DATA_TYPE = 'varbinary'
              THEN '@' + COLUMN_NAME + ' ' + DATA_TYPE + '(' + CAST(character_maximum_length AS VARCHAR) + ')'
              WHEN DATA_TYPE = 'varchar'
              THEN '@' + COLUMN_NAME + ' ' + DATA_TYPE + '(' + CAST(character_maximum_length AS VARCHAR) + ')'
              WHEN DATA_TYPE = 'xml'
              THEN '@' + COLUMN_NAME + ' ' + DATA_TYPE
       END )           + ','
FROM   INFORMATION_SCHEMA.Columns
WHERE  TABLE_NAME = @TableName

SET @ParamNames = LEFT(@ParamNames, LEN(@ParamNames)-1)
PRINT @ParamNames


Re Written Query

DECLARE @TABLE_NAME VARCHAR(50) = 'ContractMaster',
@DATA_TYPE  VARCHAR(50) = 'numeric'

SELECT paremeters       = ('@' + column_name + ' ' +
CASE
WHEN data_type   = 'BIGINT'
OR     data_type = 'Bit'
OR     data_type = 'Date'
OR     data_type = 'DateTime'
OR     data_type = 'DateTime2'
OR     data_type = 'DateTimeOffset'
OR     data_type = 'geography'
OR     data_type = 'geometry'
OR     data_type = 'hierarchyid'
OR     data_type = 'image'
OR     data_type = 'smalldatetime'
OR     data_type = 'sql_variant'
OR     data_type = 'time'
OR     data_type = 'timestamp'
OR     data_type = 'uniqueidentifier'
OR     data_type = 'xml'
THEN data_type
WHEN data_type   = 'binary'
OR     data_type = 'Char'
OR     data_type = 'NCHAR'
OR     data_type = 'NVARCHAR'
OR     data_type = 'text'
OR     data_type = 'varbinary'
OR     data_type = 'varchar'
THEN data_type + '(' + CAST(character_maximum_length AS VARCHAR) + ')'
WHEN data_type   = 'Decimal'
OR     data_type = 'money'
OR     data_type = 'numeric'
OR     data_type = 'smallmoney'
THEN data_type + '(' + CAST(numeric_precision AS VARCHAR) + ',' + CAST(numeric_scale AS VARCHAR) + ')'
WHEN data_type   = 'float'
OR     data_type = 'int'
OR     data_type = 'REAL'
OR     data_type = 'smallint'
OR     data_type = 'tinyint'
THEN data_type + '(' + CAST(numeric_precision AS VARCHAR) + ')'
ELSE data_type
END) + ' ,'
FROM   information_schema.columns
WHERE  table_name = @TABLE_NAME
AND
(
CASE
WHEN
(
@DATA_TYPE IS NULL
OR     @DATA_TYPE       = ''
)
THEN 1
END       = 1
OR     data_type = @DATA_TYPE
)


Re Written Query
DECLARE @TableName AS         VARCHAR(200)
DECLARE @TableName AS         VARCHAR(200)
DECLARE @ParamNames AS        VARCHAR(8000)
DECLARE @HorizontalTabChar AS CHAR(1)
DECLARE @NewLineChar AS       CHAR(2)
SET @TableName         = 'TableTest'
SET @HorizontalTabChar = CHAR(9)
SET @NewLineChar       = CHAR(13) + CHAR(10)
SET @ParamNames        = REPLICATE(@HorizontalTabChar, 3)
SELECT @ParamNames     = @ParamNames + '@' + syscolumns.name + ' ' + t.name + CAST( (
                     CASE
                            WHEN COLUMNPROPERTY(OBJECT_ID(@TableName), syscolumns.name, 'Scale') IS NOT NULL
                            THEN '('  + CAST(COLUMNPROPERTY(OBJECT_ID(@TableName), syscolumns.name, 'Precision') AS VARCHAR) + ',' + CAST(COLUMNPROPERTY(OBJECT_ID(@TableName), syscolumns.name, 'Scale')AS VARCHAR) + ')'
                            ELSE '('  + CAST( COLUMNPROPERTY(OBJECT_ID(@TableName), syscolumns.name, 'Precision')AS VARCHAR) +')'
                     END) AS VARCHAR) + ',' + @NewLineChar + REPLICATE(@HorizontalTabChar, 3)
FROM   sysobjects
       JOIN syscolumns
       ON     sysobjects.id = syscolumns.id
       INNER JOIN systypes t
       ON     syscolumns.xusertype = t.xusertype
WHERE  sysobjects.ID               = OBJECT_ID(@TableName)
SET @ParamNames                    = LEFT(@ParamNames, LEN(@ParamNames)-6)
PRINT @ParamNames

Another One Not Much Confident
DECLARE @TABLE_NAME VARCHAR(50) 
SET @TABLE_NAME =  'tabletest'

SELECT '@' + syscolumns.name + ' ' + UPPER(systypes.name) + ' ' +
       CASE
              WHEN syscolumns.prec    IS NULL
              AND    syscolumns.scale IS NULL
              THEN '(' + CAST(syscolumns.length AS VARCHAR) + ')'
              WHEN syscolumns.prec    = 0
              AND    syscolumns.scale = 0
              THEN '(' + CAST(syscolumns.length AS VARCHAR) + ')'
              WHEN syscolumns.prec    > 0
              AND    syscolumns.scale = 0
              THEN ''--CAST(syscolumns.length AS VARCHAR)
              WHEN syscolumns.prec          = 0
              AND    syscolumns.scale IS NULL
              THEN '(' + CAST(syscolumns.length AS VARCHAR) + ')'
              WHEN syscolumns.prec          > 0
              AND    syscolumns.scale IS NULL
              THEN '(' + CAST(syscolumns.length AS VARCHAR) + ')'
              ELSE '(' + CAST(syscolumns.prec AS   VARCHAR) + ' ,' + CAST(syscolumns.scale AS VARCHAR) + ')'
       END
FROM   sysobjects
       JOIN syscolumns
       ON     sysobjects.id = syscolumns.id
       JOIN systypes
       ON     syscolumns.xtype=systypes.xtype
WHERE  sysobjects.xtype       ='U'
AND    sysobjects.name        = @TABLE_NAME

Tuesday, November 17, 2009

Find the tables which does not have an Identity Key column

 
SELECT isc.table_name
FROM information_schema.columns AS isc
INNER JOIN sys.tables
ON SYS.tables.object_id = object_id(isc.TABLE_NAME)
WHERE SYS.tables.type = 'u'
GROUP BY isc.table_name
HAVING MAX(COLUMNPROPERTY( OBJECT_ID(isc.table_name), isc.column_name,'Isidentity')) =0--( To get the table which doesnot contains identity columns')
ORDER BY isc.table_name

Monday, November 16, 2009

Find the index of row in DataTable

string query = "Year = " + "2000" + " AND Period = " + "'1'";

int rowIndex = dtSaveAll.Rows.IndexOf(dtSaveAll.Select(query)(0));

Find all SQL Identity columns

 
SELECT '['+table_schema+'].['+table_name+'] .['+column_name+']'AS SchemaTable,
table_name ,
column_name ,
ordinal_position ,
data_type
FROM information_schema.columns
WHERE columnproperty(object_id(table_schema + '.' + table_name), column_name,'IsIdentity') = 1
ORDER BY table_name


SELECT '['+table_schema+'].['+table_name+'] .['+column_name+']'AS SchemaTable,
table_name ,
column_name ,
ordinal_position ,
data_type ,
Seed_Value AS SeedValue ,
Increment_Value AS IncrementValue ,
ident_current(Object_Name(ic.Object_ID)) AS CurrentValue ,
Last_Value AS LastValue
FROM information_schema.columns AS isc
INNER JOIN sys.identity_columns AS ic
ON ic.object_id = OBJECT_ID('['+isc.table_schema+'].['+isc.table_name+']')
INNER JOIN sys.tables
ON SYS.tables.object_id = ic.object_id
WHERE columnproperty(object_id(isc.table_schema + '.' + table_name), column_name,'IsIdentity') = 1 --( To get the table which contains only identity columns')
AND SYS.tables.type = 'u'
ORDER BY table_name


Thursday, November 5, 2009

Find table and index name for fragmented indexes


;
WITH GetFragmatation AS
( SELECT object_id AS ObjectID ,
OBJECT_NAME(object_id) AS TableName ,
index_id AS IndexID ,
avg_fragmentation_in_percent AS PercentFragment,
fragment_count AS TotalFrags ,
avg_fragment_size_in_pages AS PagesPerFrag ,
page_count AS NumPages
FROM sys.dm_db_index_physical_stats(DB_ID('RKPMS'), NULL, NULL, NULL , 'DETAILED')
WHERE avg_fragmentation_in_percent > 0
)
SELECT gf.ObjectID ,
'['+SCHEMA_NAME(schema_id)+'].['+Sch.name+']' AS FullName,
gf.TableName ,
gf.IndexID ,
IND.name AS IndexName ,
gf.PercentFragment ,
gf.TotalFrags ,
gf.PagesPerFrag ,
gf.NumPages
FROM GetFragmatation AS gf
INNER JOIN sys.indexes AS ind
ON ind.object_id = gf.ObjectID
AND index_id = gf.IndexID
INNER JOIN sys.tables AS Sch
ON Sch.object_id = gf.ObjectID
--Use the below one to defragment the Index
ALTER INDEX PK_TableNameIndexName
ON [dbo].[TableName]REBUILD WITH ( FILLFACTOR = 70, ONLINE = ON )

--To alter all the index for a table
--ALTER INDEX ALL ON TableName REBUILD




SELECT object_name(IPS.object_id) AS [TableName],
SI.name AS [IndexName],
IPS.Index_type_desc,
IPS.avg_fragmentation_in_percent AS [Percentage of the logical index that is fragmented],
IPS.avg_fragment_size_in_pages AS [Average number of pages in a leaf-level fragment.],
IPS.avg_page_space_used_in_percent,
IPS.record_count AS [Total number of records],
IPS.ghost_record_count,
IPS.fragment_count AS [Number of fragments in the leaf level.],
IPS.avg_fragment_size_in_pages AS PagesPerFrag,
IPS.page_count AS [Number of index or data pages.]
FROM sys.dm_db_index_physical_stats(db_id(N'Rkpms'), NULL, NULL, NULL , 'DETAILED') IPS
JOIN sys.tables ST WITH (nolock) ON IPS.object_id = ST.object_id
JOIN sys.indexes SI WITH (nolock) ON IPS.object_id = SI.object_id AND IPS.index_id = SI.index_id
WHERE ST.is_ms_shipped = 0 AND ST.TYPE = 'U'
ORDER BY 4 DESC

List Everything in My Database

 
SELECT B.Name as TableName,A.name as TriggerName
FROM sysobjects A,sysobjects B
WHERE A.xtype='TR'
AND A.parent_obj = B.id



Here are the list of all possible values for this column (xtype):

C = CHECK constraint

D = Default or DEFAULT constraint

F = FOREIGN KEY constraint

L = Log

P = Stored procedure


PK = PRIMARY KEY constraint (type is K)

RF = Replication filter stored procedure

S = System table

TR = Trigger

U = User table


UQ = UNIQUE constraint (type is K)

V = View

X = Extended stored procedure




To list the triggers
 

SELECT S2.[name] TableName, S1.[name] TriggerName,
CASE
WHEN S2.deltrig = s1.id THEN 'Delete'
WHEN S2.instrig = s1.id THEN 'Insert'
WHEN S2.updtrig = s1.id THEN 'Update'
END 'TriggerType' , 'S1',s1.*,'S2',s2.*
FROM sysobjects S1 JOIN sysobjects S2 ON S1.parent_obj = S2.[id] WHERE S1.xtype='TR'

Monday, October 12, 2009

Path

Making Sense of ASP.NET Paths
Full URL : http://localhost:2000/virtual_dir/myrep/page.aspx?q=qvalue
Original Path















































































Request.ApplicationPath :

/virtual_dir

Request.CurrentExecutionFilePath :

/virtual_dir/myrep/page.aspx

Request.FilePath :

/virtual_dir/myrep/page.aspx

Request.Path :

/virtual_dir/myrep/page.aspx

Request.PhysicalApplicationPath :

d:\Inetpub\wwwroot\Websitename\virtual_dir\

Request.QueryString :

/virtual_dir/myrep/page.aspx?q=qvalue

Request.Url.AbsolutePath :

/virtual_dir/myrep/page.aspx

Request.Url.AbsoluteUri :

http://localhost:2000/virtual_dir/myrep/page.aspx?q=qvalue

Request.Url.Host :

localhost

Request.Url.Authority :

localhost:2000

Request.Url.LocalPath :

/virtual_dir/myrep/page.aspx

Request.Url.PathAndQuery :

/virtual_dir/myrep/page.aspx?q=qvalue

Request.Url.Port :

2000

Request.Url.Query :

?q=qvalue

Request.Url.Scheme :

http

Request.Url.Segments :

/


virtual_dir/


myrep/


page.aspx

Wednesday, October 7, 2009

Custom PrimaryKey Based on IdentityValue

 
CREATE TABLE [dbo].[PrimaryKeyTest](
[ID] [int] IDENTITY (1,1),
[PKV] [nchar](50) NOT NULL
) ON [PRIMARY]

GO


DECLARE @CustomPKV NVARCHAR(50)

SELECT @CustomPKV = (
CASE WHEN (ISNULL(MAX(Id), -1) = -1) THEN 1
WHEN MAX(Id) >= 1 THEN MAX(Id) + 1
END
)
FROM [dbo].[PrimaryKeyTest]

PRINT @CustomPKV

INSERT INTO [dbo].[PrimaryKeyTest] (PKV) VALUES(@CustomPKV)


SELECT ID, PKV FROM [dbo].[PrimaryKeyTest]


--To CHAR DATA TYPE 'R' + CAST(
--(CASE WHEN (ISNULL(MAX(Id), -1) = -1) THEN 1
-- WHEN MAX(Id) >= 1 THEN MAX(Id) + 1
--END) AS VARCHAR)

Thursday, October 1, 2009

Numeric Validation in Javascript

/*
NUMERIC
prefix --> For number of digits before .(Period)
If you didn't give the period also it allows only the digits that given in the prefix part

suffix --> For the number of digits after the .(Period)

NumberOnly
If we specify suffix as 0 it allows only integer
*/

  
function NumericValidation(ctrlName, e, prefix, suffix) {

var evt = e || window.event;
var code = e.charCode ? e.charCode : e.keyCode;
var EndKey = 35;
var HomeKey = 36;
var NumeriPeriodKey = 110;
var PeriodKey = 190;
if (e.shiftKey || e.ctrlKey) {
return false;
}


//debugger;
// IE
if (evt.type == 'keydown') {

if ((code == EndKey || code == HomeKey || code == 37 || code == 38 || code == 39 || code == 40 || code == 9)) {
return true;
}

if (code == 46 || code == 8) {
var val = ctrlName.value;
var pos = val.indexOf('.');
var lenofBox = val.length;

if (code == 8) {
//Since back key deletes backward
if (doGetCaretPosition(ctrlName) == (pos + 1)) {

ctrlName.value = val.substring(0, pos)
}
else {
return true;
}
}
else (code == 46)
{
//Since del key deletes forward
if (doGetCaretPosition(ctrlName) == pos) {

ctrlName.value = val.substring(0, pos)
}
else {
return true;
}
}
}

if ((evt.keyCode >= 48 && evt.keyCode <= 57) || (evt.keyCode >= 96 && evt.keyCode <= 105) || (code == PeriodKey || code == NumeriPeriodKey)) {

var val = ctrlName.value;

if (val != "") {
var pos = val.indexOf('.');
var lenofBox = val.length;

//To allow only int
if ((suffix == 0) && (code == PeriodKey || code == NumeriPeriodKey)) {
return false;
}

//if already period is available
if ((code == PeriodKey || code == NumeriPeriodKey) && (pos > -1)) {
return false;
}

//if prefix reaches and the current one is not period the stop the event
if ((pos == -1 && lenofBox == prefix) && (code != PeriodKey && code != NumeriPeriodKey)) {
return false;
}

if (doGetCaretPosition(ctrlName) > pos) {

if (pos > -1) {
var decSting = val.substring(pos + 1, lenofBox + 1);
// debugger;
//alert(doGetCaretPosition(document.getElementById('TextBox1')));
if (decSting.length == suffix) {
return false;
}
}
}
else if (pos >= prefix) {
return false;
}

}

// alert(document.getElementById('TextBox1').value + String.fromCharCode(evt.keyCode));
return true;
}
else {
// alert(document.getElementById('TextBox1').value);
return false;
}
}
else if (evt.type == 'keypress') {

if ((code == 37 || code == 38 || code == 39 || code == 40) || (code == 46 || code == 8 || code == 9)) {
return true;
}

if ((evt.keyCode >= 48 && evt.keyCode <= 57) || (evt.keyCode >= 96 && evt.keyCode <= 105) || (code == PeriodKey || code == NumeriPeriodKey)) {

var val = ctrlName.value;

if (val != "") {
var pos = val.indexOf('.');
var lenofBox = val.length;

//To allow only int
if ((suffix == 0) && (code == PeriodKey || code == NumeriPeriodKey)) {
return false;
}

//if already period is available
if ((code == PeriodKey || code == NumeriPeriodKey) && (pos > -1)) {
return false;
}

//if prefix reaches and the current one is not period the stop the event
if ((pos == -1 && lenofBox == prefix) && (code != PeriodKey || code != NumeriPeriodKey)) {
return false;
}

if (doGetCaretPosition(ctrlName) > pos) {

if (pos > -1) {
var decSting = val.substring(pos + 1, lenofBox + 1);
// debugger;
//alert(doGetCaretPosition(document.getElementById('TextBox1')));
if (decSting.length == suffix) {
return false;
}
}
}
else if (pos >= prefix) {
return false;
}
}

// alert(document.getElementById('TextBox1').value + String.fromCharCode(evt.keyCode));
return true;
}
else {
// alert(document.getElementById('TextBox1').value);
return false;
}
}
}

function doGetCaretPosition(ctrl) {
var CaretPos = 0; // IE Support
if (document.selection) {
ctrl.focus();
var Sel = document.selection.createRange();
Sel.moveStart('character', -ctrl.value.length);
CaretPos = Sel.text.length;
}
// Firefox support
else if (ctrl.selectionStart || ctrl.selectionStart == '0') CaretPos = ctrl.selectionStart;
return (CaretPos);
}

Numeric Validation in Javascript





/* Babu Kumarasamy
NUMERIC
prefix --> For number of digits before .(Period)
If you didn't give the period also it allows only the digits that given in the prefix part

suffix --> For the number of digits after the .(Period)

NumberOnly
If we specify suffix as 0 it allows only integer
*/


function NumericValidation(ctrlName, e, prefix, suffix) {

var evt = e || window.event;
var code = e.charCode ? e.charCode : e.keyCode;
var EndKey = 35;
var HomeKey = 36;
var NumeriPeriodKey = 110;
var PeriodKey = 190;
if (e.shiftKey || e.ctrlKey) {
return false;
}


//debugger;
// IE
if (evt.type == 'keydown') {

if ((code == EndKey || code == HomeKey || code == 37 || code == 38 || code == 39 || code == 40 || code == 9)) {
return true;
}

if (code == 46 || code == 8) {
var val = ctrlName.value;
var pos = val.indexOf('.');
var lenofBox = val.length;

if (code == 8) {
//Since back key deletes backward
if (doGetCaretPosition(ctrlName) == (pos + 1)) {

ctrlName.value = val.substring(0, pos)
}
else {
return true;
}
}
else (code == 46)
{
//Since del key deletes forward
if (doGetCaretPosition(ctrlName) == pos) {

ctrlName.value = val.substring(0, pos)
}
else {
return true;
}
}
}

if ((evt.keyCode >= 48 && evt.keyCode <= 57) || (evt.keyCode >= 96 && evt.keyCode <= 105) || (code == PeriodKey || code == NumeriPeriodKey)) {

var val = ctrlName.value;

if (val != "") {
var pos = val.indexOf('.');
var lenofBox = val.length;

//To allow only int
if ((suffix == 0) && (code == PeriodKey || code == NumeriPeriodKey)) {
return false;
}

//if already period is available
if ((code == PeriodKey || code == NumeriPeriodKey) && (pos > -1)) {
return false;
}

//if prefix reaches and the current one is not period the stop the event
if ((pos == -1 && lenofBox == prefix) && (code != PeriodKey && code != NumeriPeriodKey)) {
return false;
}

if (doGetCaretPosition(ctrlName) > pos) {

if (pos > -1) {
var decSting = val.substring(pos + 1, lenofBox + 1);
// debugger;
//alert(doGetCaretPosition(document.getElementById('TextBox1')));
if (decSting.length == suffix) {
return false;
}
}
}
else if (pos >= prefix) {
return false;
}

}

// alert(document.getElementById('TextBox1').value + String.fromCharCode(evt.keyCode));
return true;
}
else {
// alert(document.getElementById('TextBox1').value);
return false;
}
}
else if (evt.type == 'keypress') {

if ((code == 37 || code == 38 || code == 39 || code == 40) || (code == 46 || code == 8 || code == 9)) {
return true;
}

if ((evt.keyCode >= 48 && evt.keyCode <= 57) || (evt.keyCode >= 96 && evt.keyCode <= 105) || (code == PeriodKey || code == NumeriPeriodKey)) {

var val = ctrlName.value;

if (val != "") {
var pos = val.indexOf('.');
var lenofBox = val.length;

//To allow only int
if ((suffix == 0) && (code == PeriodKey || code == NumeriPeriodKey)) {
return false;
}

//if already period is available
if ((code == PeriodKey || code == NumeriPeriodKey) && (pos > -1)) {
return false;
}

//if prefix reaches and the current one is not period the stop the event
if ((pos == -1 && lenofBox == prefix) && (code != PeriodKey || code != NumeriPeriodKey)) {
return false;
}

if (doGetCaretPosition(ctrlName) > pos) {

if (pos > -1) {
var decSting = val.substring(pos + 1, lenofBox + 1);
// debugger;
//alert(doGetCaretPosition(document.getElementById('TextBox1')));
if (decSting.length == suffix) {
return false;
}
}
}
else if (pos >= prefix) {
return false;
}
}

// alert(document.getElementById('TextBox1').value + String.fromCharCode(evt.keyCode));
return true;
}
else {
// alert(document.getElementById('TextBox1').value);
return false;
}
}
}

function doGetCaretPosition(ctrl) {
var CaretPos = 0; // IE Support
if (document.selection) {
ctrl.focus();
var Sel = document.selection.createRange();
Sel.moveStart('character', -ctrl.value.length);
CaretPos = Sel.text.length;
}
// Firefox support
else if (ctrl.selectionStart || ctrl.selectionStart == '0') CaretPos = ctrl.selectionStart;
return (CaretPos);
}

/* Babu Kumarasamy */

Friday, August 14, 2009

DataTable Creation


    public class DataTableHelper
    {
        /// 
        /// To Create Table Skeleton.
        /// 
        /// Table Column Name as an Array/// Column DataType as an Array/// Name of the DataTable/// 
        public DataTable CreateDataTable(string[] ColumnName, string[] DataType, string TableName)
        {
            // Create DataTable.   
            DataTable table = new DataTable(TableName);
            try
            {
                for (int i = 0; i < ColumnName.Length; i++)
                {
                    // Create DataColumns and add them to DataTable.   
                    table.Columns.Add(CreateDataColumn(DataType[i].Trim(), ColumnName[i].Trim(), "Column", false, false, false));
                }
            }
            catch (Exception)
            {
            }
            return table;
        }

        /// 
        /// To create the table structure
        /// 
        /// Column DataType/// ColumnName/// Column Caption/// Is Auto Increament/// IsReadOnly/// /// 
        private DataColumn CreateDataColumn(string colType, string name, string caption, bool autoInc, bool readOnly, bool unique)
        {
            DataColumn column = new DataColumn();
            try
            {
                column.DataType = System.Type.GetType(colType);
                column.ColumnName = name;
                column.Caption = caption;
                column.AutoIncrement = autoInc;
                column.ReadOnly = readOnly;
                column.Unique = unique;
            }
            catch (Exception)
            {
            }

            return column;
        }

        /// 
        /// Add Row to a DataTable
        /// //How to Call?
        /// //tempDt = oblDataTableHelper.AddRowsToTable(strArrField, tempDt);
        /// 
        /// Column Data as String Array/// Name of DataTable to add the Row/// 
        public DataTable AddRowsToTable(string[] value, DataTable table)
        {
            // Generate row with values for each column.   
            DataRow row = table.NewRow();
            try
            {
                //Add values to the columns
                for (int i = 0; i < value.Length; i++)
                    row[i] = value[i];

                // Add row to table.   
                table.Rows.Add(row);
            }
            catch (Exception)
            {
            }

            return table;
        }

        /// 
        /// Check whether the table contains Duplicate value for a particular column
        /// 
        /// DataTable/// Name of Column to Check for Duplicate/// 
        public bool HasDuplicates(DataTable table, string columnName)
        {
            bool IsContainsDuplicates = false;
            try
            {
                Hashtable hTable = new Hashtable();

                foreach (DataRow row in table.Rows)
                    if (!hTable.Contains(row[columnName]))
                        hTable.Add(row[columnName], null);
                    else
                    {
                        IsContainsDuplicates = true;
                        break;
                    }
            }
            catch (Exception)
            {
            }

            return IsContainsDuplicates;
        }

        /// 
        /// Remove rows for certains columns contains duplicate value
        /// //How to Call?
        /// tempDt = oblDataTableHelper.RemoveDuplicateRows(tempDt, new System.Collections.Generic.List(ColumnName));
        /// 
        /// DataTable Instance/// ColumnName as List/// 
        public DataTable RemoveDuplicateRows(DataTable table, List keyColumns)
        {
            //DataTable results = myDataTable.AsEnumerable().Distinct().CopyToDataTable();

            DataTable duplicateTable = table.Clone();
            DataColumn[] primaryKey = new DataColumn[duplicateTable.Columns.Count];
            duplicateTable.Columns.CopyTo(primaryKey, 0);
            duplicateTable.PrimaryKey = primaryKey;

            DataRow[] dataRows = new DataRow[table.Rows.Count];
            table.Rows.CopyTo(dataRows, 0);
            foreach (DataRow dataRow in dataRows)
                if (duplicateTable.Rows.Contains(dataRow.ItemArray))
                    table.Rows.Remove(dataRow);
                else
                    duplicateTable.Rows.Add(dataRow.ItemArray);

            return table;
        }

        //tempDt = oblDataTableHelper.RemoveDuplicateRows(tempDt, ColumnName);
        /// 
        /// Remove rows for certains columns contains duplicate value
        /// 
        /// DataTable Instance/// ColumnName as Array/// 
        public DataTable RemoveDuplicateRows(DataTable dTable, string[] strColumns)
        {
            // create a dv from the source dt 
            DataView dv = new DataView(dTable);
            // set the output columns array of the destination dt 
            // true = yes, i need distinct values. 
            return dv.ToTable(true, strColumns);
        }
    }
Calling The Function
DataTableHelper oblDataTableHelper = new DataTableHelper();
string[] ColumnName = new string[] { "Column1", "Column2", "Column3", "Column4" };
string[] DataType = new string[] { "System.String", "System.String", "System.String", "System.String" };
System.Data.DataTable tempDt = null;
tempDt = oblDataTableHelper.CreateDataTable(ColumnName, DataType, "DataTableName");
Path that gives me the idea

Monday, August 10, 2009

Failed to load viewstate. The control tree into which viewstate is being loaded must match the control tree that was used to save viewstate during

Failed to load viewstate.
match the control tree that was used to save viewstate
during the previous request. For example, when adding
controls dynamically, the controls added during a
post-back must match the type and position of the
controls added during the initial request.

This occurs in when press the command field(Edit button)
in the gridview.

To solve we have to bind the GridView once again.


 
protected void GridView1_RowEditing(object sender,
System.Web.UI.WebControls.GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindGrid();
}

Thursday, July 30, 2009

Image to Byte Array and Byte Array to Image

http://www.codeproject.com/KB/recipes/ImageConverter.aspx
 
public byte[] imageToByteArray(System.Drawing.Image imageIn)
{
MemoryStream ms = new MemoryStream();
imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);
return ms.ToArray();
}

public Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;
}

HttpModule Execution Sequence

An application executes events that are handled by modules or user code that is defined in the Global.asax file in the following sequence:

1. BeginRequest
2. AuthenticateRequest
3. PostAuthenticateRequest
4. AuthorizeRequest
5. PostAuthorizeRequest
6. ResolveRequestCache
7. PostResolveRequestCache

After the PostResolveRequestCache event and before the PostMapRequestHandler event, an event handler (a page corresponding to the request URL) is created.

8. PostMapRequestHandler
9. AcquireRequestState
10. PostAcquireRequestState
11. PreRequestHandlerExecute

The event handler is executed.

12. PotRequestHandlerExecute
13. ReleaseRequestState
14. PostReleaseRequestState

After the PostReleaseRequestState event, response filters, if any, filter the output.

15. UpdateRequestCache
16. PostUpdateRequestCache
17. EndRequest

Wednesday, July 29, 2009

byte array to bitmap

http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/e57f7731-c703-4c17-b1a2-32b155f9b745
 
public static Bitmap BytesToBitmap(byte[] byteArray)
{
using (MemoryStream ms = new MemoryStream(byteArray))
{
Bitmap img = (Bitmap)Image.FromStream(ms);
return img;
}
}


TypeConverter tc = TypeDescriptor.GetConverter(typeof(Bitmap));

Bitmap bitmap1 = (Bitmap)tc.ConvertFrom(byteArray);

Or,



ImageConverter ic = new ImageConverter();

Image img = (Image)ic.ConvertFrom(byteArray);

Bitmap bitmap1 = new Bitmap(img);

Friday, July 24, 2009

Tips

Tip #1 How to behold the power of incremental search

Command: Edit.IncrementalSearch

Shortcut: Ctrl+i

Tip #2 Ctrl+F3 to search for currently-selected word

Command: Edit.FindNextSelected

Tip #3 F3 to search for last thing you searched for

Command: Edit.FindNext

Tip #4 Customize what files to find in

Find In Files – Look in – Choose Search Folders

Tip #5 You can use a reg hack for customizing search results

HKCU\Software\Microsoft\VisualStudio\9.0\Find String Find=$f$e($l,$c):$t\r\n

Editing Tips

Tip #6 How not to accidentally copy a blank line

Tools – Options – Text Editor – All Languages – General, Uncheck Apply cut or copy to blank lines

Tip #7 How to cycle through the Clipboard ring

Command: Edit.CycleClipboardRing

Shortcut: Ctrl+Shift+v

Tip #8 How to use box/column selection in the editor

Command: Edit.LineUpColumnExtend, Edit.LineDownColumnExtend, Edit.CharRightColumnExtend, Edit.CharLeftColumnExtend

Shortcut: Shift+Alt+Arrow

Tip #9 You can copy a file’s full path / open windows explorer from the file tab channel

Command: File.CopyFullPath

Tip #10 Drag and drop code onto the toolbox’s general tab

Shortcut: Ctrl+Alt+x

Tip #11 You can use Ctrl+. to show a smart tag

Command: View.ShowSmartTag

Tip #12 You can insert a snippet by pressing Tab Tab

Type in snippet shortcut, then press Tab Tab

Customizing Tips

Tip #13 You can create temp or throw away projects

Tools - Options - Projects and Solutions - General, uncheck Save new projects when created

Tip #14 Change text editor font size via keyboard (Accessibility macros)

Command: Macros.Samples.Accessibility.DecreaseTextEditorFontSize

Command: Macros.Samples.Accessibility.IncreaseTextEditorFontSize

Tip #15 How to open a file without any UI

Ctrl+/ (or whatever Tools.GoToCommandLine is bound to)

alias fo file.openfile

fo

Tip #16 Guidelines in the editor registry key hack

HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\9.0\Text Editor String RBG(128,0,0) 5, 20

Tip #17 You can create a macro for your import/export settings

Tools – customize – commands – macros – drag and drop macro to toolbar

Tip #18 How to not show the start page (or have the last loaded solution open)

Tools - Options - Environment - Startup, At Startup

Tip #19 File tab channel registry hack

HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\9.0 key, you can create a DWORD UseMRUDocOrdering = 1

Tip #20 How to show Misc Files Project to keep your files around

tools - options - environment – documents, show miscellaneous files in Solution Explorer

Tip #21 Edit project file from within IDE (unload project)

Unload project, edit project, reload project

Debugging Tips

Tip #22 You can use tracepoints to log stuff in your code

Right-click in indicator margin, select breakpoints, select Insert Tracepoint

Tip #23 How to get the find source dialog back

Solution Properties, under Common Properties - Debug Source Files, Delete Do no look for these source files edit box contents

Tip #24 You can disable the exception assistant

Tools – Options – Debugging – General, uncheck Enable the Exception Assistant

DatabindExpressions

Digging Into Data Binding Expressions

The case of the "Eval" should be maintained. ie. "E" should be CAPS and remaining should be small.
<%#Eval("ProductName")%>,<%#FormatPrice(Eval("UnitPrice"))%>

'<%#DataBinder.Eval(Container.DataItem,"ID")%>'

'<%# Eval("ID")%>'

'<%# Eval("HotelAmenities").ToString().Replace("±","") %>'

'<%# Eval("PropertyID", "Javascript:window.open(\"Map.aspx?PID={0}\")") %>'

Call a function from the aspx page when binding using "Eval"


ImageUrl ='<%# LoadImage(Convert.ToInt32(((System.Data.DataRowView)Container.DataItem)["StarRate"]),3) %>'

LoadImage => Function Name with two parameters starrate and imagenumber

Convert.ToInt32(((System.Data.DataRowView)Container.DataItem)["StarRate"]) => Convert "StarRate" to int


Concat String with "Eval"

Text='<%# "Customer Review: "+ ((System.Data.DataRowView)Container.DataItem)["CustomerRatings"].ToString()+"/5" %>'



PostBackUrl='<%# "~/HotelDetails.aspx?PropertyID=" + Eval("PropertyID") %> '

OR
PostBackUrl="'<%# "~/HotelDetails.aspx?PID=" + Eval("PropertyID") %> '"


PostBackUrl="~/SysAdmin/modifyAnnouncement.aspx?id=<%# Eval("intAnnouncementID")%>"
PostBackUrl="~/HotelDetails.aspx?PropertyID=<%# Eval("PropertyID")%>"

PostBackUrl="~/HotelDetails.aspx?PropertyID=" + '<%# Eval("ID")%>'

PostBackUrl='<%# Eval("PropertyID", "~/HotelDetails.aspx?PropertyID={0}") %>'


DataBinder.Eval versus Explicit Casting

http://unboxedsolutions.com/sean/archive/2005/03/06/455.aspx

http://weblogs.asp.net/rajbk/archive/2004/07/20/what-s-the-deal-with-databinder-eval-and-container-dataitem.aspx


As a regular DataBinder.Eval() user, now I feel a little
bit guilty after reading this KB article, and I'm curious
how many ASP.NET developers use explicit casting on a regular basis.
Drop me a line and let me know.

Let's say you are binding to a DataSet. This...

<%# ((System.Data.DataRowView)Container.DataItem)["au_id"] %>

...is significantly faster than this...

<%# DataBinder.Eval(Container.DataItem, "au_id") %>


Conditions with Eval


<%#(DataBinder.Eval(Container.DataItem, "checkedout" ) == "No"), ?"Check Out":""%>


'<%# !String.IsNullOrEmpty(Convert.ToString(((System.Data.DataRowView)Container.DataItem)["RackRate"] ).Trim()) ? "£ "+((System.Data.DataRowView)Container.DataItem)["RackRate"]:"" %>'


PopUpS
------

OnClientClick='<%# Eval("PropertyID", "Javascript:popupWin(\"Map.aspx?PID={0}\",500,400)") %>'


OnClientClick='<%# Eval("PropertyID", "Javascript:window.open(\"Map.aspx?PID={0}\")") %>'

OR

onClientClick='<%#String.Format("{0}\"{1}{2}{3}{4}\")", "javascript:window.open(","Map.aspx?PID=",Eval("PropertyID"), "&Guid=",Eval("GUID")) %>'

OnClientClick="popup(' <%# ((System.Data.DataRowView)Container.DataItem)["PropertyID"] %>');"

OnClientClick='<%# Eval("PropertyID", "Javascript:window.open(\"Map.aspx?PropertyID={0}\")") %>'


OnClientClick='<%# Eval('PropertyID', "Javascript:window.open('Map.aspx?PropertyID={0}','top=200,left=350,width=425,height=350, menubar=no,status=no,location=yes,toolbar=no,scrollbars=no')") %>'


"window.open(<%# DataBinder.Eval(Container.DataItem,"PropertyID","'Map.aspx?PID={0}'") %>,'question','scrollbars=yes,width=630,height=480,location=no,menubar=no,status=no,toolbar=no');"

Thursday, July 23, 2009

Char to String to Byte Conversion

     
// C# to convert a string to a char array.
static public char[] convertStringToCharArray(string str)
{
return str.ToCharArray();
}

// C# to convert a string to a byte array.
static public byte[] convertStringToByteArray(string str)
{
byte[] arrByte = new byte[str.ToCharArray().Length];
int i = 0;
foreach (char ch in str.ToCharArray())
{
arrByte[i] = (byte)ch;
i++;
}
return arrByte;
}

// C# to convert a string to a byte array.
public static byte[] convertStringToByteArray1(string str)
{
//http://geekswithblogs.net/waynerds/archive/2006/01/16/66056.aspx
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
return encoding.GetBytes(str);
}


// C# to convert a string to a byte array.
public static byte[] convertStringToByteArray2(string str)
{
//http://pankajkm.blogspot.com/2007/02/convert-string-to-byte-array-and-vice.html
return (new System.Text.UnicodeEncoding()).GetBytes(str);
}

// C# to convert a char array to a byte array.
static public byte[] convertCharArrayToByteArray(char[] ca)
{
byte[] arrByte = new byte[ca.Length];
int i = 0;
foreach (char ch in ca)
{
arrByte[i] = (byte)ch;
i++;
}
return arrByte;
}

// C# to convert a char array to a string.
static public string convertCharArrayToString(char[] ca)
{
string str;
str = ca.ToString(); //Or
str = new string(ca);
return str;
}

// C# to convert a byte array to a char array.
static public char[] convertByteArrayToCharArray(byte[] by)
{
//byte[] by = { 0x01, 0x02, 0x03 };
char[] chararray = new char[by.Length];
Array.Copy(by, chararray, by.Length);
return chararray;
}



// C# Convert a byte array to a string
public static string ConvertByteArrayToString(byte[] byteArray)
{
//http://geekswithblogs.net/waynerds/archive/2006/01/16/66056.aspx
byte[] dBytes = byteArray;
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
string str = enc.GetString(dBytes);
return str;
}

// C# Convert a byte array to a string
public static string ConvertByteArrayToString1(byte[] byteArray)
{
//http://pankajkm.blogspot.com/2007/02/convert-string-to-byte-array-and-vice.html
return (new System.Text.UnicodeEncoding()).GetString(byteArray);
}

// C# Convert a byte array to a string
public static string ConvertByteArrayToString2()
{
System.Net.WebClient webdata = new System.Net.WebClient();
const string sampleurl = "http://www.sampleurl.com/default.htm";

//the below statement assigns byte[]
byte[] byteArray = webdata.DownloadData(sampleurl);

//the below code converts byte[] type string type
string txt = System.Text.Encoding.GetEncoding("utf-8").GetString(byteArray);
return txt;
}

Friday, July 10, 2009

http to https conversion

protected void Page_Init(object sender, EventArgs e)
{
string fileName = System.IO.Path.GetFileName(HttpContext.Current.Request.FilePath);
//File name that you want to give Scheme Http to Https
if (fileName == "Register.aspx" || fileName == "MyAccount.aspx")
{
HttpToHttpsConvertor(HttpContext.Current.Request.Url, true);
}
else if (System.IO.Path.GetExtension(HttpContext.Current.Request.Path) == ".aspx")
{
//Remove Scheme Https to Http
HttpToHttpsConvertor(HttpContext.Current.Request.Url, false);
}
}

protected static void HttpToHttpsConvertor(Uri uri, Boolean isHttps)
{
UriBuilder secureUriBuilder = new UriBuilder(uri);

if (isHttps)
{
if (!HttpContext.Current.Request.IsLocal)
{
if (secureUriBuilder.Scheme == Uri.UriSchemeHttp)
{
secureUriBuilder.Scheme = Uri.UriSchemeHttps;
HttpContext.Current.Response.Status = "301 Moved Permanently";
secureUriBuilder.Port = 443;
HttpContext.Current.Response.AddHeader("Location", secureUriBuilder.ToString());
HttpContext.Current.Response.Redirect(secureUriBuilder.ToString());
}
}

}
else
{
if (!HttpContext.Current.Request.IsLocal)
{
if (secureUriBuilder.Scheme == Uri.UriSchemeHttps)
{
secureUriBuilder.Scheme = Uri.UriSchemeHttp;
secureUriBuilder.Port = 80;
HttpContext.Current.Response.AddHeader("Location", secureUriBuilder.ToString());
HttpContext.Current.Response.Redirect(secureUriBuilder.ToString());
}
}
}
}

Error 1

Data Transfer Interrupted

The connection to www.XXXXX.com:80 was interrupted while the page was loading.

The browser connected successfully, but the connection was interrupted while transferring information. Please try again.
  • Are you unable to browse other sites? Check the computer's network connection.
  • Still having trouble? Consult your network administrator or Internet provider for assistance.

Rectification:

Godaddy will provide a port address for SSL.
secureUriBuilder.Port = 443;

Note:

We can get all the status code http://status-code.com/



Error 2

XML Parsing Error: no element found
Location: http://www.XXXXX.com:443/Home.aspx
Line Number 1, Column 1:
^



Rectification:

Check whether you gave another port address for unsecure form like this.
secureUriBuilder.Port = 80;


Monday, July 6, 2009

Check whether we are in local machine or in Server

 
if (!httpContext.Request.IsLocal)
{
//If false then we are in server
}

Saturday, July 4, 2009

IE6 prompts to remember password


1. Navigate to Internet Explorer -> Tools menu -> Internet Options ->
Content tab | Personal Information section | AutoComplete button.
2. Under "Use AutoComplete for", de-select the 'User names and passwords on
forms' checkbox.
3. Click Ok to apply the setting.

The following method will clear the credentials already cached in Windows
XP joins a workgroup:
1. Open Control Panel and go into User Accounts.
2. Select the account and then choose "Manage my network passwords".
3. A "Store User Names and Passwords" dialog will appear.
4. Click Remove button to clear any passwords (for the affected sites.)

How to use the AutoComplete feature in Internet Explorer 5 and 6

Thursday, June 11, 2009

SQL SERVER DATATYPE Implict Conversion

Original Path

Another good Path

Data Types (Transact-SQL)

The data type DECIMAL and NUMERIC contains scalar value.
So when convert to this type we have to do an explicit convert
and then cast to the type DECIMAL or NUMERIC.


eg.




DECLARE @myval decimal (5, 2)

SET @myval = 193.57

PRINT CAST(CAST(@myval AS varbinary(20)) AS decimal(10,5))

Things to be Noted

DECLARE @val INTEGER

SET @val = 1000

PRINT CAST(1000 AS DECIMAL(5,1))
PRINT CAST(1000 AS DECIMAL(4,1))

--IF the PRECISION should be greater than or equal to the size of the
--value after subtracting the scalar value from the precision.
--DECIMAL(Fixed PRECISION, scale numbers) Otherwise this error occurs.
--Arithmetic overflow error converting VARCHAR to data type NUMERIC.

DECLARE @test AS INT
SET @test = 10000000

--PRINT CAST(@test AS DATETIME)
--The above commented query gives the error
--Arithmetic overflow error converting expression TO data type datetime.
--This TIME we have TO USE CONVERT AND NOT cast.

PRINT CONVERT(CHAR(8), DATEADD(second, @test, ''), 114)

Links That I Like

Inside ASP.NET Runtime

Inside IIS and ASP.NET


Inside ASP.NET Runtime

URL Rebasing and MasterPages

ASP.NET Cookies

OR Another one from msdn
ASP.NET Cookies

GridView

Custom Grouping and Record Indexing

When to Use the DataGrid, DataListor Repeater

Erros

Invalid postback or callbackargument.

Validation of viewstate MAC failed error.

The application domain in which the thread was running has been unloaded

Exploring Session in ASP.Net

Beginner's Guide To View State


Beginner's Guide to ASP.NET ApplicationFolder

Maintain GridView Scroll Position
and Header Inside Update Panel


Exploring Caching in ASP.NET

Creating an Internationalized Wizard in WPF

WPF Amazon Explorer Using 3D


A lot of good articles spansented by Sacha Barber


Configure and send Mail

Configure and send Mail From SQL SERVER

SQL

madhivanan

sql-server-helper

What's New in SQL Server 2008

Visual Respansentation of SQL Joins

SQL Server data structures


Data Page Structure in MS-SQL

GROUP BY Clause (SQL Server 2005 Vs 2008)

Introduction to JOINs – Basic of JOINs

SQL Server Performance

http://sqlserver-qa.net/blogs/default.aspx

A-Z Index of the SQL Server 2005 database

SQL Server DateTime Format

Exploring your database schemawith SQL

Triggers

Understanding the Basic of Triggers

Caching

Using a controller to manage static resources

Avoid Caching of Ajax Requests

Speed Up My Code

Best Practices for Speeding Up Your Web Site

50 Tips to Boost ASP.NET Performance– Part I

50 Tips to Boost ASP.NET Performance– Part II

Conditional GET and ETag implementation for ASP.NET

http://www.acmebinary.com/blog/archive/2006/09/05/252.aspx

Improve Performance of ASP.NET Web Application

Building ASP.Net Applications – Best practices

Archive for category Performance Tips

How to Improve ASP.NET UpdatePanel Performance

Tips to Improve Your ASP.NET Web site performance

Speed Up Your Site! 8 ASP.NET Performance Tips

ASP.NET Performance

Chapter 6 — Improving ASP.NET Performance

Best Practise for Improving .NET Application Performance and Scalability

Best Practices to Improve ASP.NET Web Application Performance

50 Tips to Boost ASP.NET Performance – Part I

Best Practices to Improve ASP.Net Web Application Performance.
Improve ASP.NET Web Application Performance

ASP.NET Web Site Performance Improvement

Shivprasad koirala .NET Best Practice No: 1:- Detecting High Memory consuming functions in .NET code
Cheet Sheet


VB C# Cheet Sheet

Madskristensen

http://madskristensen.net/

Compiler Error List

Tools

Fax Server Software

Instant SQL Formatter

C# Class Generator, ASP.NET Tools

Create New Database and Auto Generate .NET Code

Codes
Easily Send Emails With .NET

Sending mail with secure service layer in asp.net 3.5/2.0

How to send mail asynchronously in asp.net

Sending email through System.Net.Mail.Smtpmail in asp.net 3.5/2.0

Understanding SMTP Status Codes

Interview Point Of View

Value vs Reference Types

Event fired again when I press F5 to refresh

Trap the Browser Refresh

Preventing Duplicate Record Insertion on Page Refresh

ViewState and Readonly Property of Textbox

Logical Query Processing Phases - Order of Statement Execution

1. FROM
2. ON --Interesting Observation of ON Clause on LEFT JOIN –
How ON Clause Effects Resultset in LEFT JOIN.

3. OUTER
4. WHERE
5. GROUP BY
6. CUBE | ROLLUP
7. HAVING
8. SELECT
9. DISTINCT
10 ORDER BY
11. TOP

I have given the Execution plan for Inner join. i.e.
If we give our condition in the ON CLAUSE or in the
WHERE CLAUSE it gives the same execution plan.






But for left join the execution plan differs and
the ResulSet also differ.





For clear details read Journey to SQL Authority's the two links.


Logical Query Processing Phases – Order of Statement Execution


Interesting Observation of ON Clause on LEFT JOIN – How ON Clause Effects Resultset in LEFT JOIN