Tuesday, 23 September 2014

Oops InterView

1.) What is object oriented programming (oops) Language?                                       
oops is is a methodology to write the program where we specify the code in form of classes and objects .oops supports   three important features which are given below:
  • Encapsulation 
  • Inheritance
  • Polymorphism
Note:- Abstraction is also basic oops concepts feature.But mainly three important feature of oops.

2.) What is object based Language?                                                                                 
Object based language supports all features of oops except two features which are given below:
  • Inheritance
  • Late binding
3.) What are three principle of  an object oriented language?                                    
  • Encapsulation 
  • Inheritance
  • Polymorphism
4.) Which property of  an object oriented programming is known as data hiding or information hiding? 
Encapsulation

5.) What is Class in c#?                                                                                                        
A Class is a user-defined data type with a template that servers to define its properties.

6.) How does declare the  Class in c#?                                                                              
Syntax:
                       Class classname
                        {
        
                         }
                             
OR


                      Class classname
                        {
                              Variable declaration;
                              Method declaration;
                         }

7.) Which types of properties includes in c# class ?                                                  
  • Indexers
  • Operators
  • Constructors
  • Destructors

8.) What is instance variables  in c# ?                                                                             
Data is encapsulated in a class by placing data fields inside the body of the class .These variables are called instance variables.We can create the instance variables exactly the same way as we create local variable.
Ex. 
        Class student
            {
                   string name;           //instance variables
                   int age      ;               //instance variables
                   money   salary;     //instance variables
          
           }

9.) What is an object  in c# ?                                                                                            
An object is Run time entity of any class,structure or union.
EX.
           Class student
               {
                        int x=10;
                        int y = 20;
                        public void display()
                            {
                                  console.WriteLne(+x);
                                  console.WriteLne(+y);
                               }
                   student st = new student()         //object "st" created
                     st.display();               // Here "st" object is calling the display method of student class
                 }

10.) What is difference between object and instance ?                                                 
An instance is a declaration time entity but an object is a Run time entity in class,structure or union.

11.) What is Method and how to declare it in class ?                                               
An method is used for manipulating the data contained in the class.Methods are used always declared inside the body of the class.
EX.
         class student
           {
              string name ;
              int age ;
            public void GetData (string s,int x)
                    {
                          name = s;
                          age = x ;
                          console.WriteLine(+s);
                          console.WriteLine(+x);
                     }
            }
12.) Can we placed method definition before instance variable in c# ?                   
Yes.

13.) Can we access the variable declared in other method within  same class ?     
NO.

14.) What is access-specifier or modifier in c# ?                                                            
More Details....

15.) How can create an object of class in c# ?                                                                 
C# uses New operator to create the object of the class.
Syntax:
classname objectname = new classname();
                            OR
classname objectname;
objectname=new classname();
EX.
student st = new student();
                            OR
student st;
st = new student();

16.) Can we create more than one object of a class  in c# ?                                         
Yes, all object are independent to each other ,means each have your copy of instance variable. 

17.) What is the syntax for accessing the class member in the class ?                    
Syntax:
objectname . variable name ;
objectname.methodname(parameter-list);

18.) What is constructor in c# ?                                                                                         
A constructor is like a method,It is used to initialization of data member of the class member , when it is created.
There are some properties of constructor in c#.
  • The name of constructor should be same as class name.
  • Constructors can be public,private or protected in the class.
  • Constructor are automatically called when object of class is created.
19.) Is constructor overloading is possible in c# ?                                                       
Yes.

20.) What is partial class in c# ?                                                                                        
More Details...

21.) What is use of 'this' keyword in c# ?                                                                        
There are some reason to use this keyword in c#.which are given below:
  • If we want to refer the current member of the current class then we can use 'this ' keyword to refer that member.
  • If we want to call a specific constructor of class through another constructor of same class the we can specify 'this' keyword without constructor.
  • We can use 'this' keyword when variable name and object name is same.

22.) What is Destructor in c# ?                                                                                         
Destructor is a method that is called when a object is no more required.The name of destructor is same as the class name.It is use prefix '~' .It is used ,to deallocate the memory used by resources within the class.
More Details...

23.) Can we use Nested classes,structs,interfaces and enums  in c# ?                      
Yes.

24.) What is Constant members in class and its use in c# ?                                        
It is used to declared the data fields of class as constant
EX.
           public const int size  =200;
In above Example,member size is assigned by 200 at compile time and can not be changed later.
Constant members are implicitly static often,we can not declare them explicitly using static.
EX.
public static const int size =200;
it is wrong ,it will give compile time error.

25.) What is Readonly members in c# ?                                       
Readonly are basically used to set the constant value at run time.Once value is assigned at run time then you can not change later. 
EX.
class student
{
public readonly int x;
public static readonly int y;
public student (int a)
{
m=x;
}
static student()
{
y=50;
}
}
26) What is properties in c# ?                                                                                           
More Details..

27) What is Indexer in c# ?                                                                                                
More Details..
Note:- Indexers are sometimes referred to as 'smart arrays'.

28) What is difference between property and Indexer in c# ?                                   
  • Indexer is always an instance member whereas property can be static member.
  • A Get accessor of a property corresponds to a method with no parameters whereas a Get accessor of an indexer's method the same formal parameter as the indexer.
  • A Set accessor of a property corresponds to a method method with the same formal parameter named value,whereas a set accessor of an indexer corresponds to a method with the same formal parameter list as the indexer and the parameter named value.
  • In Indexer,If we declare a local variable with same name as an indexer parameter then it will give error.

29) What is difference between static and Non static member in c# ?                     
More Details..

30) What is Inheritance in c# ?                                                                                       
In  Inheritance, reusability is achieved by designing new classes.Means Derived class inherits the properties of parents class.
More Details..

31) What is Encapsulation in c# ?                                                                                   
More Details..

32) What is Polymorphism in c# ?                                                                                   
Polymorphism,permits the same method name to be used for different operations in different classes.
More Details..

33) What is different form of inheritance in c# ?                                                         
  • Classical inheritance
  • Containment inheritance

34) What is Classical inheritance ?                                                                                   
A classical inheritance supports the "is relationship" between two classes. In this we can create a class hierarchy such that derived class B form , from the parent class A as shown below:
35) What are  the types of Classical inheritance ?                                                       
  • Single Inheritance
  • Multiple Inheritance
  • Multilevel Inheritance
  • Hierarchical Inheritance
  • Hybrid Inheritance
36) What is Containment inheritance in c# ?                                                                
A containment Inheritance supports the "has relationship" between two classes.
EX.
class Teacher
{
..........................
}
class student
{
Teacher T; //Teacher is contained in student.
student s;
.................................................................
}

In this ,object of Teacher(T) is contained in the object of student(s).Means when we create the object of student class then we can easily access the Teacher class member without creating the object of Teacher class.

37) How can we define the subclass in c# ?                                                               
When we define any sub class then we use : (colon operators).
Syntax:
class  subclass-name : Base classname
{
variables declaration;
Method declaration;
.........................................
}

Ex.
class student :Teacher
{

.....//includes the Teacher all fields here.
.....//include your own class features.

}
Description:In above Example,if we create the object of student class then we can easily access both class member data.

38) Is inheritance is transitive in nature ?                                                                      
No.

39) Is this is valid or invalid which are given below ?                                                  
class x : y
{
....................
}
class y : z
{
....................
}
class z : x
{
....................
}
Ans.It is invalid because classes circularly depend on themselves.

40) Is this is valid or invalid which are given below ?                                                 
class x
{
class y:x
{
..........................
}
..........................
}
Ans.It is valid because class does not dependent on the classes that are enclosed.

41) What are  the properties of inheritance in c#?                                                       
  • A derived class extends its direct base class.
  • Derived class can not change or remove the definition of an inherited member.
  • Constructors and destructors are not inherited.
  • Private member of base class can not inherited in child class(derived class).
  • An instance of a class contains a copy of all instance fields declared in the class and its base class.
  • A derived class can override an inherited member.
  • An declared class can hide an inherited members.

42) What do you mean by visibility control in c#?                                                       
In c# ,four types of accessibility modifier,which may be applied to classes and members to specify their level of visibility.
  • public
  • private
  • protected
  • Internal
43) What is "By default" mode of visibility  in c#?                                                       
If we do not explicitly set any modifier with the class then it will be By default"Internal"
Internal classes are accessible within the same program assembly and not accessible from outside the assembly.
More Details...

44) Can we access the all member of base class from derived class?                        
Yes  --> if base class member are public.
No ---> if base class member are private.

45) Can we access the class member if class is private?                                               
No.

46) Can we access the class from outside if class is public and data members are public?
No.

47) What is the accessibility constraints  in c#?                                                           
  • An  accessibility domain of a member is never larger than of the class.
Ex.
class x
{
private class y
{
public int a;
}
}

we can not  access the public data 'a' from the outside the class y.
  • All base class accessibility must be at least accessible as derived class itself.
Ex.

class x
{
.....................
}
class y :x
{
......................
}
It is illegal because x is internal ,we can not access the internal class from the derived class.
  • The return type of method must be at least as accessible as method itself.
EX.
class x
{
......................
}
public class y
{
     x method()
{
.....................//accessible
}
internal x method()
{
..................//accessible
}
public A method ()
{
.....................//not accessible because public is higher than internal

}
Note:- A Method can not have an accessibility level higher than that of its return type.

48) How can access the base class constructor from the derived class                     constructor?
We can access the base class constructor using base keyword from the derived class constructor.
Ex.
using system;
class student
{
public int a;

public int b;
public student (int p,int q)  //base constructor
{
a=p;
b=q;
}
public int calculate()
{
return(a*b);
}
}
class Teacher:student //inheriting student
{
public teacher(int x,int y,int z):base(p,q)
{
int m=z;
}
public int display()
{
return(m*a*b);
}
}
public static void main()
{
Teacher t =new Teacher(15,10,5);
int area = student.show();             //base class method call
int volume = student.display(); //derived class method call
console.WriteLine("Area="+area);
console.WriteLine("Volume="+volume);
console.ReadLine();
}

49) Can we use base keyword instead of constructor logic?                                        
Yes,We use base keyword constructor as well as any sub class to access a public or protected member defined in a parent class.
Ex.
In above example ,we can access the member of base class in child class as:
base a = 20;
base b = 30;
int area = base.show()

50) What is order of execution of constructor in below example?                            
A()  class A         Base class
B()   class B         Derived class
c()  class c            derived class

51) What is method overloading in c#?                                                                           
More Details....

52) What is method Hiding in c#?                                                                                    
More Details....

53) What is abstract class and abstract method in c#?                                                
More Details....

54) What is sealed class in c#?                                                                                           
A class that can not be subclassed ,is called sealed class.

55) Can we inherit the sealed class in c#?                                                                       
No.

56) What is the use of sealed class  in c#?                                                                       
  • Sealed class is used to prevent any unwanted extensions to the class.led class allows the compiler to perform some 
  • Sealed class allows the compiler to perform some optimizations when a method of a sealed class is  invoked.
57) What is sealed methods  in c#?                                                                                   
A sealed Method is used to override an inherited virtual method with the same signature.
Ex.
class student 
{
public virtual void show()
{
console.WriteLine("Hello");
}
}
class teacher :student
(
     public sealed override void show()
{
console.writeLine("Bye");
}
}

Note:- Any derived class of 'teacher' can not further override the method show().

58) What are the types of polymorphism  in c#?                                                           
  • Operation polymorphism
  • Inclusion Polymorphism
59) What is operation polymorphism ?                                                                           
Operation polymorphism is implemented  with the help of overloaded methods and operators.
  • Method overloading
  • Operator overloading
Method overloading and operator overloading is known as  compiler binding or early binding or static binding.This also called compiler time polymorphism.

60) What is Inclusion polymorphism ?                                                                          
Inclusion polymorphism is implemented in the concept of method overriding.In method overriding we use virtual keyword.In method overriding object of class bind at run time,so it is called run time binding or late binding.It is also known as run time polymorphism.

61) What is an Identifier ?                                                                                                 
More Details........

62) What is Ad -hoc -polymorphism in c# ?                                                                    
Ad-hoc-polymorphism is another name of overloading.

63) What are benefits and goals of objected-oriented programming ?                     
  • Reliable
  • Maintainable
  • Extendable
  • Natural
  • Reusable
  • Time saving

Group by clause and Having clause In Sql Server

group by clause:-                                                                                                                                    
When we run aggregated function in select query,we get the output on the basis of all the records but if we want to use aggregated function,then we should give us output on the basis of group and column and we can used 'group by clause' before  grouping the records.If we want to keep some conditions,we can specify 'where' clause and after grouping the records if we want to some conditions then we can use 'having' clause.
There are some commands to explain the group by clause. which are given below:
1. ) First create a students table as shown below:




2. )  Use group by command as given below:
 
   select deptName,count(*) from students where salary>1000
   group by deptName
Output:-

3. ) Use group by and Having clause as given below:-

     select deptName,count(*) from students 
    group by deptName
    having COUNT(*)>1
 Output:-

4. ) Use group by , where clause and having clause as given below:-

      select deptName,count(*)as Total from students where salary >=300
      group by deptName
      having COUNT(*)>1
Output:-

ViewState, Session vs ViewState

You may save a lot of coding by maintaining the ViewState of the objects in your Web Form.

What is ViewState?
ViewState is used to maintain the state of controls during page postback and if we save any control values or anything in viewstate we can access those values throughout the page whenever it required for that check below simple example

Maintaining the ViewState

When a form is submitted in classic ASP, all form values are cleared. Suppose you have submitted a form with a lot of information and the server comes back with an error. You will have to go back to the form and correct the information. You click the back button, and what happens.......ALL form values are CLEARED, and you will have to start all over again! The site did not maintain your ViewState.
When a form is submitted in ASP .NET, the form reappears in the browser window together with all form values. How come? This is because ASP .NET maintains your ViewState. The ViewState indicates the status of the page when submitted to the server. The status is defined through a hidden field placed on each page with a <form runat="server"> control. The source could look something like this:
<form name="_ctl0" method="post" action="page.aspx" id="_ctl0">
<input type="hidden" name="__VIEWSTATE"
value="dDwtNTI0ODU5MDE1Ozs+ZBCF2ryjMpeVgUrY2eTj79HNl4Q=" />

.....some code

</form>
Maintaining the ViewState is the default setting for ASP.NET Web Forms. If you want to NOT maintain the ViewState, include the directive <%@ Page EnableViewState="false" %> at the top of an .aspx page or add the attribute EnableViewState="false" to any control.
Look at the following .aspx file. It demonstrates the "old" way to do it. When you click on the submit button, the form value will disappear:

Example

<html>
<body>

<form action="demo_classicasp.aspx" method="post">
Your name: <input type="text" name="fname" size="20">
<input type="submit" value="Submit">
</form>
<%
dim fname
fname=Request.Form("fname")
If fname<>"" Then
Response.Write("Hello " & fname & "!")
End If
%>

</body>
</html>


Here is the new ASP .NET way. When you click on the submit button, the form value will NOT disappear:

Example

Click view source in the right frame of the example to see that ASP .NET has added a hidden field in the form to maintain the ViewState
<script runat="server">
Sub submit(sender As Object, e As EventArgs)
lbl1.Text="Hello " & txt1.Text & "!"
End Sub
</script>

<html>
<body>

<form runat="server">
Your name: <asp:TextBox id="txt1" runat="server" />
<asp:Button OnClick="submit" Text="Submit" runat="server" />
<p><asp:Label id="lbl1" runat="server" /></p>
</form>

</body>
</html>


View State

- View state is maintained in page level only.
- View state of one page is not visible in another page.
- View state information stored in client only.
- View state persist the values of particular page in the client (browser) when post back operation done.
- View state used to persist page-instance-specific data.

      Session State

- Session state is maintained in session level.
- Session state value is available in all pages within a user session.
- Session state information stored in server.
- Session state persist the data of particular user in the server. This data available till user close the browser or session time completes.
- Session state used to persist the user-specific data on the server side.

      Usage

- If you want to access the information on different web pages, you can use SessionState
- If you want to access from the same page, then you can use Viewstate

     Security

     Session state provides more security when compared with view state as the data value is stored in server side

Thursday, 11 September 2014

What is a Trigger

What is a Trigger
A trigger is a special kind of a store procedure that executes in response to certain action
 on the table like insertion, deletion or updation of data. It is a database object which is bound
to a table and is executed automatically. You can’t explicitly invoke triggers. The only way to
do this
 is by performing the required action no the table that they are assigned to.
Types Of Triggers
There are three action query types that you use in SQL which are INSERT, UPDATE and DELETE. So,
there
are three types of triggers and hybrids that come from mixing and matching the events and timings
 that fire them.

Basically, triggers are classified into two main types:-

(i) After Triggers (For Triggers)
(ii) Instead Of Triggers

(i) After Triggers
These triggers run after an insert, update or delete on a table. They are not supported for views.
AFTER TRIGGERS can be classified further into three types as:

(a) AFTER INSERT Trigger.
(b) AFTER UPDATE Trigger.
(c) AFTER DELETE Trigger.

Let’s create After triggers. First of all, let’s create a table and insert some sample data. Then,
 on this table,
I will be attaching several triggers.

Collapse | Copy Code

CREATE TABLE Employee_Test
(
Emp_ID INT Identity,
Emp_name Varchar(100),
Emp_Sal Decimal (10,2)
)

INSERT INTO Employee_Test VALUES ('Anees',1000);
INSERT INTO Employee_Test VALUES ('Rick',1200);
INSERT INTO Employee_Test VALUES ('John',1100);
INSERT INTO Employee_Test VALUES ('Stephen',1300);
INSERT INTO Employee_Test VALUES ('Maria',1400);


I will be creating an AFTER INSERT TRIGGER which will insert the rows inserted into the table into
another audit table.
The main purpose of this audit table is to record the changes in the main table. This can be thought
of as a generic audit
 trigger.

Now, create the audit table as:-
Collapse | Copy Code

CREATE TABLE Employee_Test_Audit
(
Emp_ID int,
Emp_name varchar(100),
Emp_Sal decimal (10,2),
Audit_Action varchar(100),
Audit_Timestamp datetime
)

(a) AFTRE INSERT Trigger
This trigger is fired after an INSERT on the table. Let’s create the trigger as:-
Collapse | Copy Code

CREATE TRIGGER trgAfterInsert ON [dbo].[Employee_Test]
FOR INSERT
AS
    declare @empid int;
    declare @empname varchar(100);
    declare @empsal decimal(10,2);
    declare @audit_action varchar(100);

    select @empid=i.Emp_ID from inserted i;   
    select @empname=i.Emp_Name from inserted i;   
    select @empsal=i.Emp_Sal from inserted i;   
    set @audit_action='Inserted Record -- After Insert Trigger.';

    insert into Employee_Test_Audit
           (Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_Timestamp)
    values(@empid,@empname,@empsal,@audit_action,getdate());

    PRINT 'AFTER INSERT trigger fired.'
GO

The CREATE TRIGGER statement is used to create the trigger. THE ON clause specifies
 the table name on which the trigger is to be attached.
 The FOR INSERT specifies that this is an AFTER INSERT trigger. In place of FOR
INSERT, AFTER INSERT can be used. Both of them mean the same.
In the trigger body, table named inserted has been used. This table is a logical
 table and contains the row that has been inserted. I have selected the fields from
 the logical inserted table from the row that has been inserted into different variables,
 and finally inserted those values into the Audit table.
To see the newly created trigger in action, lets insert a row into the main table as :
Collapse | Copy Code

 insert into Employee_Test values('Chris',1500);


Now, a record has been inserted into the Employee_Test table. The AFTER INSERT trigger attached
to this table has
 inserted the record into the Employee_Test_Audit as:-
Collapse | Copy Code

6   Chris  1500.00   Inserted Record -- After Insert Trigger.    2008-04-26 12:00:55.700

(b) AFTER UPDATE Trigger
This trigger is fired after an update on the table. Let’s create the trigger as:-
Collapse | Copy Code

CREATE TRIGGER trgAfterUpdate ON [dbo].[Employee_Test]
FOR UPDATE
AS
    declare @empid int;
    declare @empname varchar(100);
    declare @empsal decimal(10,2);
    declare @audit_action varchar(100);

    select @empid=i.Emp_ID from inserted i;   
    select @empname=i.Emp_Name from inserted i;   
    select @empsal=i.Emp_Sal from inserted i;   
   
    if update(Emp_Name)
        set @audit_action='Updated Record -- After Update Trigger.';
    if update(Emp_Sal)
        set @audit_action='Updated Record -- After Update Trigger.';

    insert into Employee_Test_Audit(Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_Timestamp)
    values(@empid,@empname,@empsal,@audit_action,getdate());

    PRINT 'AFTER UPDATE Trigger fired.'
GO

The AFTER UPDATE Trigger is created in which the updated record is inserted into the audit table.
 There is no logical
 table updated like the logical table inserted. We can obtain the updated value of a field from
 the update(column_name) function. In our trigger, we have used, if update(Emp_Name) to check if
 the column Emp_Name has been updated. We have similarly checked the column Emp_Sal for an update.
Let’s update a record column and see what happens.
Collapse | Copy Code

 update Employee_Test set Emp_Sal=1550 where Emp_ID=6

This inserts the row into the audit table as:-
Collapse | Copy Code

6  Chris  1550.00  Updated Record -- After Update Trigger.      2008-04-26 12:38:11.843

(c) AFTER DELETE Trigger
This trigger is fired after a delete on the table. Let’s create the trigger as:-
Collapse | Copy Code

CREATE TRIGGER trgAfterDelete ON [dbo].[Employee_Test]
AFTER DELETE
AS
    declare @empid int;
    declare @empname varchar(100);
    declare @empsal decimal(10,2);
    declare @audit_action varchar(100);

    select @empid=d.Emp_ID from deleted d;   
    select @empname=d.Emp_Name from deleted d;   
    select @empsal=d.Emp_Sal from deleted d;   
    set @audit_action='Deleted -- After Delete Trigger.';

    insert into Employee_Test_Audit
(Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_Timestamp)
    values(@empid,@empname,@empsal,@audit_action,getdate());

    PRINT 'AFTER DELETE TRIGGER fired.'
GO

In this trigger, the deleted record’s data is picked from the logical deleted table and inserted
into the audit table.
Let’s fire a delete on the main table.
A record has been inserted into the audit table as:-
Collapse | Copy Code

 6  Chris    1550.00  Deleted -- After Delete Trigger.  2008-04-26 12:52:13.867

All the triggers can be enabled/disabled on the table using the statement
Collapse | Copy Code

ALTER TABLE Employee_Test {ENABLE|DISBALE} TRIGGER ALL

Specific Triggers can be enabled or disabled as :-
Collapse | Copy Code

ALTER TABLE Employee_Test DISABLE TRIGGER trgAfterDelete


This disables the After Delete Trigger named trgAfterDelete on the specified table.

(ii) Instead Of Triggers
These can be used as an interceptor for anything that anyonr tried to do on our table or view.
 If you define
an Instead Of trigger on a table for the Delete operation, they try to delete rows, and they will
 not actually
 get deleted (unless you issue another delete instruction from within the trigger)
INSTEAD OF TRIGGERS can be classified further into three types as:-

(a) INSTEAD OF INSERT Trigger.
(b) INSTEAD OF UPDATE Trigger.
(c) INSTEAD OF DELETE Trigger.

(a) Let’s create an Instead Of Delete Trigger as:-
Collapse | Copy Code

CREATE TRIGGER trgInsteadOfDelete ON [dbo].[Employee_Test]
INSTEAD OF DELETE
AS
    declare @emp_id int;
    declare @emp_name varchar(100);
    declare @emp_sal int;
   
    select @emp_id=d.Emp_ID from deleted d;
    select @emp_name=d.Emp_Name from deleted d;
    select @emp_sal=d.Emp_Sal from deleted d;

    BEGIN
        if(@emp_sal>1200)
        begin
            RAISERROR('Cannot delete where salary > 1200',16,1);
            ROLLBACK;
        end
        else
        begin
            delete from Employee_Test where Emp_ID=@emp_id;
            COMMIT;
            insert into Employee_Test_Audit(Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_Timestamp)
            values(@emp_id,@emp_name,@emp_sal,'Deleted -- Instead Of Delete Trigger.',getdate());
            PRINT 'Record Deleted -- Instead Of Delete Trigger.'
        end
    END
GO

This trigger will prevent the deletion of records from the table where Emp_Sal > 1200.
If such a record is deleted,
the Instead Of Trigger will rollback the transaction, otherwise the transaction will be committed.
Now, let’s try to delete a record with the Emp_Sal >1200 as:-

Collapse | Copy Code

delete from Employee_Test where Emp_ID=4

This will print an error message as defined in the RAISE ERROR statement as:-

Collapse | Copy Code

Server: Msg 50000, Level 16, State 1, Procedure trgInsteadOfDelete, Line 15
Cannot delete where salary > 1200


And this record will not be deleted.
In a similar way, you can code Instead of Insert and Instead Of Update triggers on your tables.

Tuesday, 9 September 2014

ASP.NET – JSON – Serialization and Deserialization

I was looking around for a simple example which would just do a object serialization to a JSON format, and then deserializing back to the original object. I found few examples on MSDN, but did seem to be too long to try. Here I’ve given a simple code which would make your understanding easy, and simpler.
 
Before going into the code, let us first understand what is JSON, and what is its significance in the modern world of web applications.
 
What is JSON?
 
JSON is another format of expressing data, just like XML. But, JSON is very simpler than XML, and tiny than XML. So, it is becoming popular in the web world to choose the JSON notation over XML since JSON notation are usually shorter, and less data to be transmitted if at all they were to be.
 
Okay, I understood a little about JSON. Give me an example!
 
I know an example will get your understanding much better. Below is a simple example of how an object can be expressed in JSON notation. Let’s take a classical example of a Person object, and expressing myself as an object.
{
   “firstName”: “Rakki”,
   “lastName”:”Muthukumar”,
   “department”:”Microsoft PSS”,
   “address”: {
      “addressline1”: “Microsoft India GTSC”,
      “addressline2”: “PSS - DSI”,
      “city”: “Bangalore”,
      “state”: “Karnataka”,
      “country”: “India”,
      “pin”: 560028
   }
   “technologies”: [“IIS”, “ASP.NET”,“JavaScript”,“AJAX”]
}
In the above example, address is another object inside my Person, and technologies is an array or strings.
 
Express this as a simple .NET class, please!
 
Here is a simple example.
public class Address
{
    public string addressline1, addressline2, city, state, country;
    public int pin;
}
 
public class Person
{
    public string firstName, lastName, department;
    public Address address = new Address();
    public string[] technologies;
}
I get it. Now what? JSON Serialization / Deserialization?
 
I’m sure you do not want me to write what is serialization, and deserialization here. I’ll touch upon how to use System.Web.Script.Serialization.JavaScriptSerializer to convert an existing object into a JSON string.
JavaScriptSerializer js = new JavaScriptSerializer();
Person p1 = new Person();
p1.firstName = "Rakki";
p1.lastName = "Muthukumar";
p1.department = "Microsoft PSS";
p1.address.addressline1 = "Microsoft India GTSC";
p1.address.addressline2 = "PSS - DSI";
p1.address.city = "Bangalore";
p1.address.state = "Karnataka";
p1.address.country = "India";
p1.address.pin = 560028;
p1.technologies = new string[] { "IIS", "ASP.NET", "JavaScript", "AJAX" };
 
string str = js.Serialize(p1);
Above code just creates a Person object, and assign some values. Look at the last line where we are actually doing a serialization – means dumping the contents of the object to a JSON notation. Below is the string produced by the above code:
{"firstName":"Rakki","lastName":"Muthukumar","department":"Microsoft PSS","address":{"addressline1":"Microsoft India GTSC","addressline2":"PSS - DSI","city":"Bangalore","state":"Karnataka","country":"India","pin":560028},"technologies":["IIS","ASP.NET","JavaScript","AJAX"]}
It is the same as how we defined the object before – but in a single line. Now, you have successfully converted your object into a JSON string.
Now how do I deserialize it?
 
Before going into how to deserialize it, let’s just understand when you might want to deserialize the object. Classical example is a JSON object returned from a web service, or from your client side javascript code, and you will be able to deserialize it in the server side to use the received object. 
Person p2 = js.Deserialize<Person>(str);
Response.Write(p2.lastName);
p2.lastName would contain “Muthukumar” if your deserialization works fine. I suggest you to use the Deserialize<T> method since it will reduce the type casting you might be doing if you use DeserializeObject() method which returns a System.Object.

Monday, 8 September 2014

Accessing ASP.NET Session variable using Javascript:

 //Set Session Value
<script type="text/javascript">
function SetUserName()
{
    var userName = "Shekhar Shete";
    '<%Session["UserName"] = "' + userName + '"; %>';
     alert('<%=Session["UserName"] %>');
}
</script>

//Get Session Value



<script type="text/javascript">
    function GetUserName()
    {
        var username = '<%= Session["UserName"] %>';
        alert(username );
    }
</script>

Wednesday, 3 September 2014

Difference Between DataReader, DataSet, DataAdapter and DataTable in C#


DataReader
DataReader is used to read the data from database and it is a read and forward only connection oriented architecture during fetch the data from database. DataReader will fetch the data very fast when compared with dataset. Generally we will use ExecuteReader object to bind data to datareader.
To bind DataReader data to GridView we need to write the code like as shown below:
Protected void BindGridview()
{
using (SqlConnection conn = new SqlConnection("Data Source=abc;Integrated Security=true;Initial Catalog=Test"))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select UserName, First Name,LastName,Location FROM Users", conn);
SqlDataReader sdr = cmd.ExecuteReader();
gvUserInfo.DataSource = sdr;
gvUserInfo.DataBind();
conn.Close();
}
}
  • Holds the connection open until you are finished (don't forget to close it!).
  • Can typically only be iterated over once
  • Is not as useful for updating back to the database
DataSet
DataSet is a disconnected orient architecture that means there is no need of active connections during work with datasets and it is a collection of DataTables and relations between tables. It is used to hold multiple tables with data. You can select data form tables, create views based on table and ask child rows over relations. Also DataSet provides you with rich features like saving data as XML and loading XML data.
protected void BindGridview()
{
    SqlConnection conn = new SqlConnection("Data Source=abc;Integrated Security=true;Initial Catalog=Test");
    conn.Open();
    SqlCommand cmd = new SqlCommand("Select UserName, First Name,LastName,Location FROM Users", conn);
    SqlDataAdapter sda = new SqlDataAdapter(cmd);
    DataSet ds = new DataSet();
    da.Fill(ds);
    gvUserInfo.DataSource = ds;
    gvUserInfo.DataBind();
}
DataAdapter
DataAdapter will acts as a Bridge between DataSet and database. This dataadapter object is used to read the data from database and bind that data to dataset. Dataadapter is a disconnected oriented architecture. Check below sample code to see how to use DataAdapter in code:
protected void BindGridview()
{
    SqlConnection con = new SqlConnection("Data Source=abc;Integrated Security=true;Initial Catalog=Test");
    conn.Open();
    SqlCommand cmd = new SqlCommand("Select UserName, First Name,LastName,Location FROM Users", conn);
    SqlDataAdapter sda = new SqlDataAdapter(cmd);
    DataSet ds = new DataSet();
    da.Fill(ds);
    gvUserInfo.DataSource = ds;
    gvUserInfo.DataBind();
}
  • Lets you close the connection as soon it's done loading data, and may even close it for you automatically
  • All of the results are available in memory
  • You can iterate over it as many times as you need, or even look up a specific record by index
  • Has some built-in faculties for updating back to the database.
DataTable

DataTable represents a single table in the database. It has rows and columns. There is no much difference between dataset and datatable, dataset is simply the collection of datatables.

protected void BindGridview()
{
     SqlConnection con = new SqlConnection("Data Source=abc;Integrated Security=true;Initial Catalog=Test");
     conn.Open();
     SqlCommand cmd = new SqlCommand("Select UserName, First Name,LastName,Location FROM Users", conn);
     SqlDataAdapter sda = new SqlDataAdapter(cmd);
     DataTable dt = new DataTable();
     da.Fill(dt);
     gridview1.DataSource = dt;
     gvidview1.DataBind();
}



DataReader
===========
DataReader is like a forward only recordset. It fetches one row at a time so very less network cost compare to DataSet(Fethces all the rows at a time). DataReader is readonly so we can't do any transaction on them. DataReader will be the best choice where we need to show the data to the user which requires no transaction. As DataReader is forward only so we can't fetch data randomly. .NET Data Providers optimizes the datareader to handle huge amount of data.

DataSet
=======
DataSet is an in memory representation of a collection of Database objects including tables of a relational database schemas.
DataSet is always a bulky object that requires a lot of memory space compare to DataReader. We can say that the DataSet is a small database because it stores the schema and data in the application memory area. DataSet fetches all data from the datasource at a time to its memory area. So we can traverse through the object to get the required data like querying database.