Total Pageviews

Thursday, April 16, 2009

Browser detection javascript

heres a javascript for the detection of the web browser used by the end user:


if(navigator.userAgent.indexOf(’Safari’)!=-1)
{ 
    alert(’safari’); 
} 
else if(navigator.userAgent.indexOf(’Gecko’)!=-1) 
{ 
    alert(’mozilla’); 
}  
else 
{ 
    if(navigator.userAgent.indexOf(’MSIE 7.0′)!=-1) 
    { 
        alert(’ie 7′); 
    } 
    else 
    { 
        alert(’ie 6′); 
    } 
}         
       

now i’ll explain you the above script: navigator.userAgent returns the full description of the user agent or web browser used by the client or end user. indexOf() function returns the character position [...]

Regular Expression in Sqlserver 2005


Regular Expression in Sqlserver 2005.

why Regular Expression Required for sqlserver 2005? The basic need Of Regular Expression
is avoiding hard work for searching or pattern maching in database. Example if i
want to search valid email address from users table then what will be senario for
that? i have thousand of newly registered user daily. then how to i find invalid
Email Address from that? let’s start with regular expression in sqlserver 2005.
the basic requirement for that configure OLE Object in to Server. –Configure OLE
Automation object. –EXECUTE permission set for object ’sp_OACreate’

use[master] GO GRANT EXECUTE ON[sys].[sp_OASetProperty] TO [public] 
GO 
use[master] 
GO 
GRANT EXECUTE ON[sys].[sp_OAMethod] TO[public] 
GO use[master] 
GO GRANT EXECUTE ON[sys].[sp_OAGetErrorInfo] TO[public] 
GO use[master] 
GO GRANT EXECUTE ON[sys].[sp_OADestroy] TO[public] 
GO use[master] 
GO GRANT EXECUTE ON[sys].[sp_OAStop] TO[public] 
GO use[master] 
GO GRANT EXECUTE ON[sys].[sp_OACreate] TO[public] 
GO use[master] 
GO GRANT EXECUTE ON[sys].[sp_OAGetProperty] TO[public] 
GO sp_configure’show advanced options’,1 
GO reconfigure go  execsp_configure go execsp_configure‘Ole Automation Procedures’,
        

1 – Configuration option ‘Ole Automation Procedures’ changed from 0 to 1. Run the
RECONFIGURE statement to install. go reconfigure go steps : 1) Create Scalar Value
Function In Sqlserver 2005.


create FUNCTION dbo.RegEx     
(         
 --Expression Target / Source         
 @Target varchar(5000),         
 --Regular Expression Pattern         
 @Pattern varchar(Max),         
 --whether the expression case sensitive         
 @CaseSensitive bit = 0     
) 
RETURNS bit 
AS     
BEGIN         
DECLARE @ReturnOACreate int         
DECLARE @ObjToken int         
DECLARE @objMatches int         
DECLARE @objMatch int         
DECLARE @count int         
DECLARE @results bit          

EXEC @ReturnOACreate = sp_OACreate 'VBScript.RegExp', @ObjToken OUTPUT          
--objecttoken OUTPUT         
--Is the returned object token, and must be a local variable of data type int.         
--This object token identifies the created OLE object and is used in calls to the other         
--OLE Automation stored procedures.         
--Return         
--0 (success) or a nonzero number (failure) that is the integer value of the         
--HRESULT returned by the OLE Automation object          
IF @ReturnOACreate <> 0 
BEGIN             
    SET @results = 0             
    RETURN @results         
END          
EXEC @ReturnOACreate = sp_OASetProperty @ObjToken, 'Pattern', @Pattern          
IF @ReturnOACreate <> 0 
BEGIN             
    SET @results = 0             
    RETURN @results         
END          
EXEC @ReturnOACreate = sp_OASetProperty @ObjToken, 'Global', false         
IF @ReturnOACreate <> 0 
BEGIN             
    SET @results = 0             
    RETURN @results         
END          
EXEC @ReturnOACreate = sp_OASetProperty @ObjToken, 'IgnoreCase', @CaseSensitive         
IF @ReturnOACreate <> 0 
BEGIN             
    SET @results = 0             
    RETURN @results         
END              
EXEC @ReturnOACreate = sp_OAMethod @ObjToken, 'Test', @results OUTPUT, @Target         
IF @ReturnOACreate <> 0 
BEGIN             
    SET @results = 0             
    RETURN @results         
END          
EXEC @ReturnOACreate = sp_OADestroy @ObjToken         
IF @ReturnOACreate <> 0 
BEGIN             
    SET @results = 0             
    RETURN @results         
END     

--return 1 for success     
RETURN @results     
END          

2) Now use this function for Matching the Expression.


  • case 1: simple regular expression match
            select dbo.RegEx( N'122-45-6789', N'^\d{3}-\d{2}-\d{4}$',0 )      
            run this it return 0 it indicate this expression is valid.  
        
            select dbo.RegEx( N'1224-45-6789', N'^\d{3}-\d{2}-\d{4}$',0 )      
            run this it return 1 it indicate this expression is InValid.  
            

  • case 2: Get the data from Table now the senario is i am finding the valid email address from the table (here i used simple regular expression which is made manual for demo purpose you can use any of them.)
        declare @tblTmp as table(id int identity(1,1),emailaddress varchar(50))  
        insert into @tblTmp values ('test@yahoo') 
        insert into  @tblTmp values ('test@gmail.test') 
        insert into @tblTmp values ('t@gmail.com') 
        insert into @tblTmp values ('test@test.com') 
        insert into  @tblTmp values ('test@test.')  
        
        select * from @tblTmp  
        --find valid email address 
        
        select * from @tblTmp where dbo.RegEx(emailaddress,'^[A-Za-z0-9._%-]+@[a-zA-Z0-9]+\.[a-zA-Z]{2,4}$',0)=1
        

Wednesday, April 15, 2009

Split Function in SQL Server

Sql Server does not (on my knowledge) have in-build Split function. Split function
in general on all platforms would have comma-separated string value to be split
into individual strings. In sql server, the main objective or necessary of the Split
function is to convert a comma-separated string value (‘abc,cde,fgh’) into a temp
table with each string as rows.

The below Split function is Table-valued function which would help us splitting
comma-separated (or any other delimiter value) string to individual string.

Create FUNCTION [dbo].[Split]
( 
 @String varchar(8000), @Delimiter char(1)
)
returns @temptable TABLE (items varchar(8000)) 
as 
begin 

declare @idx int 
declare @slice varchar(8000) 

select @idx = 1 

if len(@String)<1 or @String is null 
 return 

while @idx!= 0 
begin 
 
 set @idx = charindex(@Delimiter,@String)  
 if @idx!=0 
  set @slice =left(@String,@idx - 1) 
 else 
  set @slice = @String 

 if(len(@slice)>0) 
  insert into @temptable(Items)values(@slice) 

 set @String = right(@String,len(@String) - @idx) 
 if len(@String)= 0 
 break 
end 
return 
end 

--now fire this query 
select top 10 * from dbo.split('Chennai,Bangalore,Mumbai',',')

--this will return following results. 
-- Items -----------------------
--Chennai 
--Bangalore 
--Mumbai

Tuesday, April 14, 2009

SQL Native Client (SQLNCLI )

SQl server uses a new database provider model. This provider succeeds OLEDB. OLEDB
was used for SQL Server databases. Now even it's possible to access MS Access databases
that way. ODBC is only for backward compatability. The new SQLNCLI provider has
the following new features

  • - Support for the new SLQ 2005 large datatypes (Max String, with no limited length)
  • - XML Datatype (Not just a handle, but a real type)
  • - Custom Datatypes (UDT)
  • - The new snapshot isolation level.This level does not lock dirty reads. It uses
    optimistic (locking). It's the best of both worlds. Enabled to read all actual committed
    data, skipping locks, but reading the data (dirty reads),and persisting data if
    the data is not locked.
  • - Supprot for multiple active recordsets. It was already possible to get multiple
    recordsets. In Ado.Net, with movenext, the next result could be read. But now, it's
    possible to have multiple connections open. So each recordset (multiple retrieval)
    can have it's own connection.
  • - Password can be changed at the client, without the need of the administrator.
  • - Support for asynchoon operations. Lots of complex database actions take a time.
    Now SQL server can create threads to do jobs on its own.
  • - It supports SQLXML 4.0. The new connection string (just another provider) "Provider=SQLNCLI;Server=(local);Database=Northwind;IntegratedSecurity=SSPI;" For DSN connections (who uses them still?) "Driver={SQL Native Client}; Server=(local); Database=Northwind; Trusted_Connection=yes;"

Saturday, April 11, 2009

Export GridView into Excel

below i am describing how to export a grid data..
    /// pass gridveiw into this funtion  
    private void ExportGridView(GridView gv)
    {
        string attachment = "attachment; filename=ArchiveOrderList.xls"; //name of excel filename         
        Response.ClearContent();
        Response.AddHeader("content-disposition", attachment);
        Response.ContentType = "application/ms-excel";
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        // Create a form to contain the grid         
        HtmlForm frm = new HtmlForm();
        //gvOrderInfo.Parent.Controls.Add(frm);         
        //gvOrderInfo.Parent.Controls.Add(frm);         
        this.Controls.Add(frm);
        frm.Attributes["runat"] = "server";
        frm.Controls.Add(gv);
        frm.RenderControl(htw);
        //GridView1.RenderControl(htw);         
        Response.Write(sw.ToString());
        Response.End();
    }

    private void PrepareGridViewForExport(Control gv)
    {
        LinkButton lb = new LinkButton();
        Literal l = new Literal();
        string name = String.Empty;
        for (int i = 0; i < gv.Controls.Count; i++)
        {
            if (gv.Controls[i].GetType() == typeof(LinkButton))
            {
                l.Text = (gv.Controls[i] as LinkButton).Text;
                gv.Controls.Remove(gv.Controls[i]);
                gv.Controls.AddAt(i, l);
            }
            else if (gv.Controls[i].GetType() == typeof(DropDownList))
            {
                l.Text = (gv.Controls[i] as DropDownList).SelectedItem.Text;
                gv.Controls.Remove(gv.Controls[i]);
                gv.Controls.AddAt(i, l);
            }
            else if (gv.Controls[i].GetType() == typeof(CheckBox))
            {
                l.Text = (gv.Controls[i] as CheckBox).Checked ? "True" : "False";
                gv.Controls.Remove(gv.Controls[i]);
                gv.Controls.AddAt(i, l);
            }
            else if (gv.Controls[i].GetType() == typeof(ImageButton))
            {
                continue;
            }
            if (gv.Controls[i].HasControls())
            {
                PrepareGridViewForExport(gv.Controls[i]);
            }
        }
    }

    public override void VerifyRenderingInServerForm(Control control)
    {
        if (control.ID == GridView1.Id) // here GridView1 is the id of gridview of page
        {
            //Doing nothing             
            return;
        }
        base.VerifyRenderingInServerForm(control);
    }

Thursday, April 2, 2009

Open New pop window

hay guys nothing to new...use java script to open new pop up window on image button
click or any other window... just add attribute like ...
    imgbtn.Attributes.Add("onclick", "javascript:window.open('" + Text.Replace(" ", "_") + "/LargeImage.aspx?data=" + str + "','LargeImage','width=500,height=500,scrollbars=yes'); return false;");   
    //here imgbtn is my image control name

Blog Archive

Ideal SQL Query For Handling Error & Transcation in MS SQL

BEGIN TRY BEGIN TRAN --put queries here COMMIT; END TRY BEGIN CATCH IF @@TRANCOUNT>0 BEGIN SELECT @@ERROR,ERRO...