Friday, May 14, 2010

JAVA SCRIPT

1./* Create A Text File(If Not Exists) Through Java Script Containing WorkstationId and Telephone No on BodyOnload */

/--------- Start------------/

function fileexist()
{
var file=new ActiveXObject("Scripting.FileSystemObject");
if(file.FileExists("C:\\wstationfile.txt"))
{
var tempFile=file.OpenTextFile("C:\\wstationfile.txt",1,false,0);
var line= tempFile.ReadAll();
var newindex=line.indexOf("/");
var oldindex=0;
var str,restofstr;
restofstr=line;
while (restofstr.indexOf("/")>0)
{
str=restofstr.substring(0,newindex);
restofstr=restofstr.substring(newindex+1,restofstr.length);
newindex=restofstr.indexOf("/");
if(str.substring(0,str.indexOf("-")).toUpperCase()=="STATIONID")
{
document.getElementById("txtstation").value=str.substring(str.indexOf("-") + 1,str.length);
}
else if (str.substring(0,str.indexOf("-")).toUpperCase()=="TELEPHONENO")
{
document.getElementById("txttelephone").value=str.substring(str.indexOf("-") + 1,str.length);
}
str="";
}
document.getElementById("txttelephone").readOnly=true;
document.getElementById("txtstation").readOnly=true;
}
else
{
document.getElementById("txttelephone").readOnly=false;
document.getElementById("txtstation").readOnly=false;
}
}
function createfile()
{
var create,file;
create=new ActiveXObject("Scripting.FileSystemObject");
file=create.CreateTextFile("C:\\wstationfile.txt",true);
var str="";
str="stationid-" + document.getElementById("txtstation").value + "/";
str = str + "telephoneno-" + document.getElementById("txttelephone").value + "/";
str= str + "user-" + document.getElementById("txtusername").value + "/";
str = str + "campaing-GERECOVERY/" ;
str = str + "Lastdate-" + Date() + "/";
file.WriteLine(str);
}
/-------End--------------/



2./* Purpose:Display Month in Combo on Change of Year */

/--------- Start------------/
function ChangeMonth(j)
{

var m_names = new Array("January", "February", "March","April", "May", "June", "July", "August", "September",
"October", "November", "December");
var date=new Date();
var curr_month=date.getMonth();
var curr_year=date.getFullYear();
var curr_nextyear=curr_year + 1;;
var sel_year=document.getElementById('selYear' + j);;
var list=document.getElementById('selMonth' + j);;
var i;

if (document.getElementById('selYear' + j).value==curr_nextyear)//Purpose:If Year is Next Year,Month will start from Jan till dec
{
list=document.getElementById('selMonth' + j);    
for(i = 0; i < 12; i++)    {      list.options[i] = new Option(m_names[i].toString(),i); } } if (document.getElementById('selYear' + j).value==curr_year)//Purpose:If Year is Current Year,Month will start from Current Month till Dec { list.options.length=0; for(i=curr_month;i < 12; i++) {     list.options[i] = new Option(m_names[i].toString(),i);     }     if (list.options.length >0 )
{
for(var l=list.options.length-1;l>=0;l--)
{
if(list.options[l].value=="")
{
list.remove(l);
}
}
}

}
/--------- End------------/

3./*Purpose:To Check Java Script is Enable or Not */
function CheckJavaScript() {

if (navigator.JavaEnabled())
{
alert("The javascript is available .")
return true;
}
else
{
return false ;
}
}

4./* Purpose:Allow Only Numbers From 0 to 9 */

function onlyNumbers(evt)
{
var e = event || evt; // for trans-browser compatibility
var charCode = e.which || e.keyCode;
//charcode=45(-) For Negative

if (charCode > 31 && (charCode < 48 || charCode > 57) || (charCode == 45))
return false;

return true;
}

5./* Purpose:To Allow Alpha Numeric Characters */

function isAlphaNumeric(elem, helperMsg)
{
var alphaExp = /^[a-zA-Z0-9]+$/;
if (elem.value != "")
{
if(elem.value.match(alphaExp)){
return true;
}
else
{
alert(helperMsg);
elem.value="";
elem.focus();
elem.select();
return false;
}
}
}

6./* Purpose:To Allow EMail Validation */

function emailValidator(elem, helperMsg){
var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
if (elem.value != "")
{
if(elem.value.match(emailExp)){
return true;
}
else
{
alert(helperMsg);
elem.focus();
elem.select();
return false;
}

Friday, March 19, 2010

SQL(Difference Between Various Things)

/* Difference b/w DataSet and DataReader */

1.DataSet is a disconnected architecture, while DataReader has live
connection while reading data. If we want to cache data and pass to a
different tier DataSet forms the best choice and it has decent XML support.

2. DataReader provides forward-only and read-only access to data,
while the DataSet object can hold more than one table
(in other words more than one rowset) from the same data source
as well as the relationships between them.
Thus,when application needs to access data from more than one
table "DataSet" forms the best choice.

3. Dataset can persist contents while datareader can not persist contents,
they are forward only.Therefore,If we need to move back while
reading records,“datareader” does not support this functionality.

4. But one of the biggest drawbacks of DataSet is speed.
As “DataSet” carry considerable overhead because of relations,
multiple tables etc speed is slower than “DataReader”. Always try to use “DataReader” wherever possible, as it’s meant specially for speed performance.

/* Difference b/w Stored Procedure and Function */

1. Functions must return a value(scalar,inline table or multi statement table) whereas stored proc may or may not retun a value.

2.Stored Procedures can have input,output parameters for it whereas functions can have only input parameters.

3.Stored Procedure allow select as well as DML statement in it whereas function allow only select statement in it.

4.Functions can be called from SP whereas procedures cannot be called from function.

5.Exception can be handled by try-catch block in a procedure whereas try-catch block cannot be used in a function.

6.We can go for transaction management in procedure whereas we can't go in function.

7.Procedures can not be utilized in a select statement whereas function can be embedded in a select statement.

8.Procedures are Parsed and Compiled during design time itself whereas Functions are Compiled and executed during run time

9.A UDF returns table variables, while a SPROC can't return a table variable although it can create a table.

10.UDFs can't change the server environment or your operating system environment, while a SPROC can

11.We can pass 1024 parameters in one stored procedure.


/* Difference b/w TRUNCATE and DELETE */

1.TRUNCATE is DDL Command, whereas DELETE is DML Command.

2.TRUNCATE removes all rows from a table, but the table structure, its columns, constraints, indexes and so on, remains,whereas DELETE removes rows one at a time and records an entry in the transaction log for each deleted row.

3.TRUNCATE Resets identity of the table whereas DELETE does not reset identity of the table.If you want to retain the identity counter, use DELETE instead like :

4.TRUNCATE cannot be rolled back,whereas DELETE can be rolled back
But if we want to Rollback with Truncate we can use this :

BEGIN TRAN
TRUNCATE TABLE tablename
ROLLBACK TRAN

5.DELETE Can be used with or without a WHERE clause,
whereas Truncate cannot be

6.You cannot use TRUNCATE TABLE on a table referenced by a
FOREIGN KEY constraint. Because TRUNCATE TABLE is not logged,
it cannot activate a trigger,whereas DELETE Activates Triggers.

/*------------------INDEXES---------------------*/

Advantages of Indexes

1.Searching For Records
2.Sorting Records.
3.Grouping Records
4.Maintaining a Unique Column

Index Drawbacks

1.Indexes and Disk Space
2.Indexes and Data Modification

Composite Indexes
A composite index is an index on two or more columns. Both clustered and nonclustered indexes can be composite indexes.

/*Difference B/W Clustered And Non Clustered Indexes */

1.clustered index is a special type of index that
reorders the way records in the table are physically stored.
Therefore table can have only one clustered index.
whereas A nonclustered index is a special type of index
in which the logical order of the index does not match the physical stored order of the rows on disk

2.The leaf nodes of a clustered index contain the data pages.
whereas The leaf node of a nonclustered index does not consist
of the data pages.Instead, the leaf nodes contain index rows.

3.If a PRIMARY KEY constraint is created for a database table and
no clustered index currently exists for that table,
SQL Server automatically creates a clustered index on the primary key.

4.For a clustered index, the database will sort the table's records
according to the column (or columns) specified by the index.

5.A clustered index contains all of the data for a table in the index,
sorted by the index key,just like a phone book is sorted by name
and contains all of the information for the person inline
whereas nonclustered indexes contain only the index key and
a reference to find the data,

6. Much like the index in the back of a book helps us to find keywords
quickly, so the database is able to quickly narrow the number of records
it must examine to a minimum by using the sorted list of UnitPrice
values stored in the index.Thats why Non Clustered Index is slow

7.SQL Server 2000 supports a maximum of 249 non-clustered indexes
per table. However, it’s important to keep in mind that non-clustered
indexes slow down the data modification and insertion process,
so indexes should be kept to a minimum

/* Difference B/w Set and Select */

1.SET is the ANSI standard way of assigning values to variables,
and SELECT is not.

2.Use SELECT to assign values to more than one variable at a time.
SET allows you to assign data to only one variable at a time.
Here's how:
/* Declaring variables */
DECLARE @Variable1 AS int, @Variable2 AS int

/* Initializing two variables at once */
SELECT @Variable1 = 1, @Variable2 = 2

/* The same can be done using SET, but two SET statements are needed */
SET @Variable1 = 1
SET @Variable2 = 2


3.one single SELECT statement can be used to assign values to
multiple variables. This very feature of SELECT makes it a
winner over SET,
when assigning values to multiple variables.
A single SELECT statement assigning values to 3 different variables,
is much faster than 3 different SET statements assigning values to 3 different variables.

In this scenario, using a SELECT is at least twice as fast, compared to SET.
So, the conclusion is, if you have a loop in your stored procedure that
manipulates the values of several variables, and if you want to squeeze
as much performance as possible out of this loop, then do all variable manipulations
in one single SELECT statement (or group the related variables into few SELECT statements)
as shown below:

SELECT @TestVar1 = @TestVar1 + 1, @TestVar2 = @TestVar2 - 1, @CTR = @CTR + 1

/* Difference B/w SQL 2008 and SQL 2005 */

1. SQL2008 has support for additional datatypes: date ; time ; geospatial  ; timestamp with internal timezone .

2. In sql server 2005,There is no option to compress backup files, but in sql server 2008,there you find it. storing backup file takes 5 minutes without compression in sqlserver 2005,but it takes only 3 minutes in sql server 2008 for storing backup files with compression. 

Therefore, CPU is used to compress the data before it is written to disk,so less data is written to disk. 

3. Server 2008 also added CMS which is Central Management Server. It only works with Windows Authentication but it allows you to management multiple SQL Servers at once. If SQL Server systems are popping up like weeds it will appear in the CMS provided that they point to the CMS via SSMS. Its a really cool feature. 

4. PBM Policy-Based Management is another added feature introduced with SQL Server 2008. PBM allows you to define and enforce policies for configuring and managing SQL Server across your enterprise. It goes hand-in-hand with CMS. 

5. One of my favorite is that fact that Reporting Services no longer requires IIS as it makes direct calls to HTTP.SYS. 

Main Difference is over 2000,2005,2008 is 
1. XML integration
2. Exception Handling
3. CLR ( common language runtime) integration
4. Varchar(Max) data type
5. DDL Triggers
6. DataBase Mirroring
7. RowNumber function for paging
8. Table fragmentation
9. Full Text Search
10. Easy User Interface
11. Versions
12. Bulk Copy Update

Wednesday, March 17, 2010

Common Functions Used in VB.Net

/* This function is to Check AlphaNumeric Charcaters */

Public Function IsAlphanumeric(ByVal strValue As String) As Boolean
Dim lngLength As Long
Dim lngCounter As Long
Dim intAsciiVal As Integer
IsAlphanumeric = True
strValue = UCase(strValue)
lngLength = Len(strValue)
For lngCounter = 1 To lngLength
intAsciiVal = Asc(Mid(strValue, lngCounter, 1))
If (intAsciiVal >= 48 And intAsciiVal <= 57) Or (intAsciiVal >= 65 And intAsciiVal <= 90) Then Else IsAlphanumeric = False Exit For End If Next End Function /*This function is used to Display Error Message.*/

Public Sub gnErrorMessage(ByVal psMsg As String, ByVal psTitle As String, Optional ByRef poCtrl As Object = Nothing)
Dim Response, DgDef, Msg, Title As Object
Dim i As Short
Call MessageBox.Show(psMsg, psTitle, MessageBoxButtons.OK, MessageBoxIcon.Error)
If Not IsNothing(poCtrl) Then
If poCtrl.Enabled = True And poCtrl.Visible = True Then
poCtrl.focus()
If TypeOf poCtrl Is TextBox Or TypeOf poCtrl Is ComboBox Then poCtrl.selectall()
End If
End If
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default
End Sub

/*This function is used to concatenate quotes before the character string.

Public Function gsTextConvert(ByVal vsStr As String) As String
If IsNothing(vsStr) Then
vsStr = ""
Else
vsStr = Trim(vsStr)
End If
If vsStr.Length <> 0 Then
gsTextConvert = "'" & Replace(vsStr, "'", "''") & "'"
Else
gsTextConvert = "NULL"
End If
End Function

/*This function is used to Convert Value in TextBox Into Upper Case.*/

Public Sub gnToUpper(ByRef pCtrl As System.Windows.Forms.TextBox)
Dim pviCurrPos As Integer
pviCurrPos = pCtrl.SelectionStart
pCtrl.Text = UCase(pCtrl.Text)
pCtrl.SelectionStart = pviCurrPos
End Sub

/*This function is used to Check The Value Should Not Be Empty */

Public Overloads Function gbEmptyChk(ByRef roCtrl As System.Windows.Forms.Control, ByVal vsMsg As String) As Boolean
Dim pvsStr As String
gbEmptyChk = True
pvsStr = Trim(roCtrl.Text)
If pvsStr = "" Then
vsMsg = vsMsg & " cannot be empty."
Call gnErrorMessage(vsMsg, "Validation", roCtrl)
Exit Function
End If
gbEmptyChk = False
End Function

/*This Function checks that the Combo Box Should Not Be Empty */

Public Overloads Function gbEmptyChk(ByRef roCtrl As System.Windows.Forms.ComboBox, ByVal vsMsg As String) As Boolean
Dim pvsStr As String
gbEmptyChk = True

If roCtrl.SelectedIndex = -1 Or Trim(roCtrl.Text).Length < 1 Then pvsStr = vsMsg & " cannot be empty." Call gnErrorMessage(pvsStr, "Validation", roCtrl) Exit Function End If gbEmptyChk = False End Function /* This subroutine is to make a connection */

Public Sub gnMakeConnection()
'//Try
gvoAdoCon = New SqlConnection()
gvoAdoCon.ConnectionString = gvsConnectionString
gvoAdoCon.Open()

''''Catch e As Exception
'''' Call gnErrorMessage(e.Message, "Make Connection")
''''End Try
End Sub


/* This subroutine is to end a connection */

Public Sub gnEndConnection()
'//Try
gvoAdoCon.Close()
gvoAdoCon = Nothing
''''Catch e As Exception
'''' Call gnErrorMessage(e.Message, "End Connection")
''''End Try
End Sub

/* This subroutine is to Begin a Transaction */

Public Function goBeginTran() As SqlClient.SqlCommand
Dim pvuCommand As New SqlClient.SqlCommand()
'''Try
gvoAdoTran = gvoAdoCon.BeginTransaction()
pvuCommand.Transaction = gvoAdoTran
goBeginTran = pvuCommand
''''Catch e As Exception
'''' Call gnErrorMessage(e.Message, "Begin Tran")
''''End Try
End Function

/* This subroutine is to Commit a Transaction */
Public Sub gnCommitTran()
Try
gvoAdoTran.Commit()
Catch ex As Exception
'// no error handling
'''' Call gnErrorMessage(e.Message, "Commit Tran")
End Try
End Sub

/* This subroutine is to Rollback a Transaction */

Public Sub gnRollbackTran()
Try
'//gvoAdoTran.Connection.tr
gvoAdoTran.Rollback()
Catch ex As Exception
'//no error handling
'''' Call gnErrorMessage(e.Message, "Rollback Tran")
End Try
End Sub

/* This function is to return a DataReader */

Public Function goPopulateDataReader(ByVal vsSQL As String, ByVal vbTran As Boolean) As SqlDataReader
Dim pvoCmd As New SqlCommand()
''''Try
With pvoCmd
.Connection = gvoAdoCon
.CommandText = vsSQL
If vbTran Then .Transaction = gvoAdoTran
goPopulateDataReader = .ExecuteReader
End With
''''Catch e As Exception
'''' Call gnErrorMessage(e.Message, "goPopulateDataReader")
''''End Try
End Function

/* This Subroutine is to Work With DataSet */

Public Sub gnPopulateDataSet(ByVal vsSQL As String, ByVal vsName As String, ByRef roDataSet As DataSet)
Dim pvoAdapt As SqlDataAdapter
''''Dim pvsSQL As String
''''Try
roDataSet = New DataSet()
pvoAdapt = New SqlDataAdapter(vsSQL, gvoAdoCon)
pvoAdapt.Fill(roDataSet, vsName)
''''Catch e As Exception
'''' Call gnErrorMessage(e.Message, "goPopulateDataSet")
''''End Try
End Sub

/* This Subroutine is to Execute a Transaction */

Public Sub gnExecuteSQL(ByVal vsSQL As String, ByVal vbTran As Boolean)
Dim pvoCmd As New SqlCommand()
'''Try
With pvoCmd
.Connection = gvoAdoCon
.CommandText = vsSQL
If vbTran = True Then .Transaction = gvoAdoTran
.ExecuteNonQuery()
End With
''''Catch e As Exception
'''' Call gnErrorMessage(e.Message, "goExecuteSQL")
''''End Try
End Sub


/* This Function is to check Duplicate Entry */

Public Function gbDuplicateCheck(ByVal vsString As String, ByVal vsCtrlName As String, ByRef roCtrl As System.Windows.Forms.Control) As Boolean
Dim pvoDR As SqlDataReader
Dim pviCount As Short
gbDuplicateCheck = True
If gbEmptyChk(roCtrl, vsCtrlName) Then Exit Function
pvoDR = goPopulateDataReader(vsString, False)
pvoDR.Read()
pviCount = pvoDR(0)
pvoDR.Close()
pvoDR = Nothing
If pviCount > 0 Then
gbDuplicateCheck = True
Call gnErrorMessage(vsCtrlName & " already exists.", "Duplicate Check", roCtrl)
Exit Function
Else
gbDuplicateCheck = False
End If
End Function

/* This subroutine is used to Remove Space */

Public Sub gnRemoveSpace(ByRef pForm As System.Windows.Forms.Form)
Dim lCtrl As Object
For Each lCtrl In pForm.Controls
If TypeOf lCtrl Is System.Windows.Forms.TextBox Then
lCtrl.Text = Trim(lCtrl.Text)
End If
Next lCtrl
End Sub

/* To set all the combobox values as blank in the form */

Private Sub gnInitializeComboControl(ByRef roControl As Control)
Dim pvuControl As Control
For Each pvuControl In roControl.Controls
If pvuControl.Controls.Count > 1 Then
Call gnInitializeComboControl(pvuControl)
Else
If TypeOf pvuControl Is ComboBox Then
CType(pvuControl, ComboBox).SelectedIndex = -1
CType(pvuControl, ComboBox).SelectedIndex = -1
End If
End If
Next
End Sub

/* To Enable/Disable Controls In One Form Throgh Other Form */

Public Sub gnEnableDisableFields(ByRef roForm As System.Windows.Forms.Form)
Dim pvuControl As Control
Dim pvuInnrControl As Control
For Each pvuControl In roForm.Controls
'//If TypeOf pvuControl Is GroupBox Then
If pvuControl.Controls.Count > 1 Then
For Each pvuInnrControl In pvuControl.Controls
If Not TypeOf pvuInnrControl Is Label Then pvuInnrControl.Enabled = False
Next
Else '//If TypeOf pvuControl Is TextBox Then
If Not TypeOf pvuControl Is Label Then pvuControl.Enabled = False
End If
Next
End Sub

/* Allow AlphaNumeric on KeyPress Event in a Text Box */

Public Sub gnAllowAlphaNumeric(ByRef roKeyChar As KeyPressEventArgs)
Select Case Asc(roKeyChar.KeyChar)
Case Asc("0") To Asc("9") '// for between 0 to 9
Case Asc("A") To Asc("Z") '// for between A to Z
Case Asc("a") To Asc("z") '// for between a to z
Case 8 '//backspace
Case Else
roKeyChar.Handled = True
End Select
End Sub

/* Allow Numeric on KeyPress Event in a Text Box */

Public Sub gnAllowNumeric(ByVal vsText As String, ByRef roKeyChar As KeyPressEventArgs, ByVal vbDecimal As Boolean)
Select Case Asc(roKeyChar.KeyChar)
Case Asc("0") To Asc("9") '// for between 0 to 9
Case 8 '//backspace
Case 46 And vbDecimal '// decimal
If InStr(vsText, ".", CompareMethod.Text) > 0 Then roKeyChar.Handled = True
Case Else
roKeyChar.Handled = True
End Select
End Sub

Tuesday, March 16, 2010

Stored Procedures

/* To Insert and Delete Multiple Id's Through SP */

CREATE procedure [dbo].[UP_TEST]
@MultipleId varchar(500)
AS
DECLARE @QUERY VARCHAR(2000)

SET @QUERY = ''
SET @QUERY = @QUERY + ' INSERT INTO T_Test_BackUp
SET @QUERY = @QUERY + ' Select * from T_TEST where id in (' + @MultipleId + ')'
SET @QUERY = @QUERY + ' delete from T_TEST where id in(' + @MultipleId + ')'

EXEC(@QUERY)

/* To Return The Latest Identity Using Output Parameter Through SP */

create proc up_InsertTest
@id int,
@ElementNo varchar(10),
@Name varchar(100),
@outputval varchar(100) = null output

as
Begin
declare @ErrorNumber int
Begin Tran
begin
insert into T_Test(id,ElementNo,Name)
VALUES(@id,@ElementNo,@Name)
set @ErrorNumber = @@Error
if (@ErrorNumber >0) goto Error_lbl
set @outputval = convert(varchar(100), IDENT_CURRENT('T_Test'))
end
Error_Lbl:
if (@ErrorNumber <> 0 )
begin
rollback tran
set @outputval= -1
return
end
End

.Net (Differences b/w various things)

(I)/* Difference Between Array Vs. ArrayList */

1.Array is a primitive data structure, which stores the values in indexed format.
whereas
ArrayList is a mere like a vector. (A re-sizeable array). It is a collection and stores any value as an object.

2.An array can be of any data type and contain one data type
while array list can contain any data type in the form of the object.
(Array is for homogeneous data. i.e data of same data type,
Whereas Arraylist is for Heterogeneous data.The data in the arraylist need not be of same data type)

3.With array you can not dynamically increase or decrease the size of array dynamically.You must the define the size of the array.You can change the size of the array with redim statement but still you have to define type.
While with array list you can make list of any sizes.
When a element or object is added to array list it size is automatically increase the capacity of the array list.It has a default size(16 items).
if u have even 1 item the size will be 16.
After 16 if u add another item, the size increases to 32.
i.e the arrayList size can be increased dynamically.

4.once you delete the item in array it kept that one as empty like a[2]="" but
in case of arraylist a[3]index occupies the position of a[2] and also if you try to insert a[2] value array will throw error if any items reside inside but in case of arraylist a[2] is inserted in same position but at the same time
position of a[2] become a[3] if there is already an item exists

/*--------------End Array VS. ArrayList----------------*/


(II)/*Difference Between String vs. StringBuilder */

1.A String object is called immutable (read-only) because its value cannot be modified once it has been created.Methods that appear to modify a String object actually return a new String object that contains the modification.
whereas
System.StringBuilder was designed with the purpose of
having a mutable string where a variety of operations can be performed.
We use StringBuilder's Append() method to use concatenation.
For eg.name = "Prasad Reddy";
A new name object is creating in memory and the value "Prasad Reddy" is assinging to the newly created space.
But StringBuilder class occupies the same space even if you change the value.

2.StringBuilder gives you better performance than String
class when you perform string manipulations like string
concatenation.
We can use StringBuilder's Append() method to use
concatenation and for String use "+".
The StringBuilder's initial capacity is set to 16 by default. The capacity then increases by an order of 2 whenever the current capacity is passed. Therefore, if the String you append to the StringBuilder causes the capacity to expand, it will
increase.

/*--------------End String VS. StringBuilder----------------*/


/*------------- Abstract Class Vs. Interface ---------------------- */

1.An abstract class is a special kind of class that cannot be instantiated. So the question is why we need a class that cannot be instantiated? An abstract class is only to be sub-classed (inherited from). In other words, it only allows other classes to inherit from it but cannot be instantiated. The advantage is that it enforces certain hierarchies for all the subclasses. In simple words, it is a kind of contract that forces all the subclasses to carry on the same hierarchies or standards

1.An interface is not a class. It is an entity that is defined by the word Interface. An interface has no implementation; it only has the signature or in other words, just the definition of the methods without the body. As one of the similarities to Abstract class, it is a contract that is used to define hierarchies for all subclasses or it defines specific set of methods and their arguments. The main difference between them is that a class can implement more than one interface but can only inherit from one abstract class. Since C# doesn�t support multiple inheritance, interfaces are used to implement multiple inheritance.

2.Abstract class is a class which contain one or more abstract methods which has to be implemented by sub classes. Inteface is a Java Object containing method declaration and doesn't contain implementation. The classes which have implementing the Interfaces must provide the method defination for all the methods.

3. Abstract class is a Class prefix wtih a abstract keyword followed by Class definaton. Interacace is a Interface which starts with interface keyword.

4. Abstract class contatins one or more abstract methods. where as Interface contains all abstract methods and final declarations.

5. Abstract class contains the method defination of the some methods. but Interface contains only method declaration no defination provided.

6. Abstract classes are useful in a situation that Some general methods should be implemented and specialization behaviour should be implemented by child classes. Interafaces are useful in a situation that all properties should be implemented we can use this scenario

/*----------------------------Both Together-----------------------*/

When we create an interface, we are basically creating a set of methods without any implementation that must be overridden by the implemented classes. The advantage is that it provides a way for a class to be a part of two classes: one from inheritance hierarchy and one from the interface.

When we create an abstract class, we are creating a base class that might have one or more completed methods but at least one or more methods are left uncompleted and declared abstract. If all the methods of an abstract class are uncompleted then it is same as an interface. The purpose of an abstract class is to provide a base class definition for how a set of derived classes will work and then allow the programmers to fill the implementation in the derived classes.


/*------------- End Abstract Class Vs. Interface ---------------------- */


/*--------------- Struct Vs. Class ----------------------------------- */

1. Classes contains a referance of the data.
whereas Struct directly contains the original data.

2. Classes are references type that required to allocate of heap.
wheras Struct are values type that do not required to allocate of heap

3. Classes can inherit from other classes and interface.
whereas Struct can inherit from interface only.

4. Classes are used to store larger data(more data 16 bytes)
whereas Struct are used to store less data(16 bytes or less)

5- To instantiate an object of a class, we use the new keyword.
whereas we do not require the new keyword to create a instane of a struct.

/*-------------------End Struct Vs. Class---------------------------*/

/*------------------Structure Vs. Class-----------------------------*/

1)Structure :- In structure have a by default public.
In class have a by default private.

2)Structure cannot be inherited. But class can be
inherit.

3)There is no data hiding features comes with
structures. Classes do, private, protected and public.

4)A structure can't be abstract, a class can.

5)A structure is a value type, while a class is a
reference type.

6)A structure is contain only data member , but class
contain data member and member function.

7)In a Structure we can't initilse the value to the
variable but in class variable we assign the values.

8)Structure are value type, They are stored as a
stack on memory. where as class are reference type. They
are stored as heap on memory.

Important Note In general, classes can be used when you have more complex behavior or data. And if you think that these behaviour or data to be modified after creating an instance of class, then classes are absolute methods. Structures can be used for small data structures. If developer feels that data members of structure cannot to be modified after creating structure, then having structure will suit. /*-------------------End Structure Vs. Class---------------------------*/

Thursday, March 11, 2010

Important SQL Queries

1./* To Copy an excel sheet(named temp in C Drive which is in the server) into a temporary table named tbltemp */(For Import)


EXEC( 'SELECT * INTO ' + 'tbltemp' + ' from OpenRowset(''Microsoft.Jet.OLEDB.4.0'',''Excel 8.0;Database=' + 'C:\temp.xls' + ''',''select * from [Sheet1$]'')')

2./* To Update a paricular column in one table by using other table */

update table1 set table1.mobile=table2.mobilephone
from table1 inner join table2 on table1.id=table2.id
where table1.cycle_flag=1

3./*To retrieve names of all the columns in table1*/

select name from syscolumns where id in (select id from sysobjects where name='table1')

4./*To retrieve column name,data type and length of each field in a table named check_length*/)

select syscolumns.name,systypes.name,syscolumns.length
from syscolumns inner join systypes on systypes.xusertype=syscolumns.xusertype
where syscolumns.id=object_id('check_length')

5./*To interchange: Where gender is Male that should be female and where Female that should be Male */

update tablename set gender=(case when gender='Male' then 'Female' else 'Male' end)

6./* To find how many tables contain ID as the column name */

select * from Information_schema.columns where column_name='ID'

7. /*To remove Duplicates Records from a table.
If you have a primary key in the table */


DELETE Authors
FROM authors auth
LEFT OUTER JOIN
(
SELECT AuthName, min(AuthorRowid) as AuthorRowid
FROM authors
GROUP BY Authorname
) gAuth
on gAuth.AuthorRowid = auth.AuthorRowid
WHERE gAuth.AuthorRowid is null


8./*To find how many book types are there for individual subject(No of Books for each subject) */

Id BookType BookName
1 Chem Organic
2 Bio lifescience
3 Phy Nootan
4 Chem Inorganic
5 Phy Bhatnagar
6 Chem Physical


select distinct(booktype),count(booktype) as 'No Of Books' from tbl_bookdetails group by booktype
or
select distinct(booktype),count(booktype) as 'No Of Books' from tbl_bookdetails group by booktype order by count(booktype)

O/P:
booktype No Of Books
Bio 1
Phy 2
Chem 3

Export To Excel in ASP.Net 2.0 From a GridView

/* Export To Excel From GridView*/
protected void Lnk_Click(object sender, EventArgs e)


{

try

{

Response.Clear();

Response.AddHeader("content-disposition", "attachment;filename=FileName.xls");

Response.Charset = "";

//Response.Cache.SetCacheability(HttpCacheability.NoCache); //Purpose:Not Allowed to Open a File Without Saving It

Response.ContentType = "application/vnd.xls";

StringWriter stringWrite = new StringWriter();

HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);

String strstyle = "";



stringWrite.GetStringBuilder().Append("<>" + "<>" + "<>" + " <>" + " <>" + "<>" + " <>" + " <>" + "<>" + " <>"); stringWrite.WriteLine(strstyle); Grid.Columns[0].Visible = false; Grid.RenderControl(htmlWrite); stringWrite.GetStringBuilder().Append("
" +

"SMS Report" +

"
" +

"
" +

"Run Date: " + DateTime.Now.Date.ToString("d") + "" +

"
");



Response.Write(stringWrite.ToString());

Response.End();

}

catch (Exception ex)

{



throw ex;

}

}

public override void VerifyRenderingInServerForm(Control control)

{

// Confirms that an HtmlForm control is rendered for the specified ASP.NET server control at run time.

//For this we override the method



}
/*Purpose:To Convert MoblieNo into Text */
int row;
for (row = 0; row <= Grid.Rows.Count - 1; row++)
{
Grid.Rows[row].Cells[4].Attributes.Add("class", "text");
//Grid.Rows[row].Cells[5].Attributes.Add("class", "text");
}

Wednesday, February 17, 2010

AJAX

AJAX = Asynchronous JavaScript and XML
AJAX is not a new programming language, but a technique for creating better, faster, and more interactive web applications.
With AJAX, your JavaScript can communicate directly with the server, using the JavaScript XMLHttpRequest object. With this object, your JavaScript can trade data with a web server, without reloading the page.
AJAX uses asynchronous data transfer (HTTP requests) between the browser and the web server, allowing web pages to request small bits of information from the server instead of whole pages.
The AJAX technique makes Internet applications smaller, faster and more user-friendly.
AJAX is a browser technology independent of web server software.
AJAX is Based on Web Standards
AJAX is based on the following web standards:
JavaScript
XML
HTML
CSS
The web standards used in AJAX are well defined, and supported by all major browsers. AJAX applications are browser and platform independent.
AJAX is About Better Internet Applications
Web applications have many benefits over desktop applications; they can reach a larger audience, they are easier to install and support, and easier to develop.
However, Internet applications are not always as "rich" and user-friendly as traditional desktop applications.
With AJAX, Internet applications can be made richer and more user-friendly.
You Can Start Using AJAX Today
There is nothing new to learn.
AJAX is based on existing standards. These standards have been used by most developers for several years.
AJAX Uses HTTP Requests
In traditional JavaScript coding, if you want to get any information from a database or a file on the server, or send user information to a server, you will have to make an HTML form and GET or POST data to the server. The user will have to click the "Submit" button to send/get the information, wait for the server to respond, then a new page will load with the results.
Because the server returns a new page each time the user submits input, traditional web applications can run slowly and tend to be less user-friendly.
With AJAX, your JavaScript communicates directly with the server, through the JavaScript XMLHttpRequest object
With an HTTP request, a web page can make a request to, and get a response from a web server - without reloading the page. The user will stay on the same page, and he or she will not notice that scripts request pages, or send data to a server in the background.
The XMLHttpRequest Object
By using the XMLHttpRequest object, a web developer can update a page with data from the server after the page has loaded!
AJAX was made popular in 2005 by Google (with Google Suggest).
Google Suggest is using the XMLHttpRequest object to create a very dynamic web interface: When you start typing in Google's search box, a JavaScript sends the letters off to a server and the server returns a list of suggestions.
The XMLHttpRequest object is supported in Internet Explorer 5.0+, Safari 1.2, Mozilla 1.0 / Firefox, Opera 8+, and Netscape 7.