Serialization in .NET?


Serialization is the process of converting an object into a form so that it can be persisted int the storage location(memory,a database or a file) or can be transported across the network.Main purpose of Serialization is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization.The object is serialized to a stream, which carries not just the data, but information about the object's type, such as its version, culture, and assembly name. From that stream, it can be stored in a database, a file, or memory.

Serailization usage:
Serialization allows the developer to save the state of an object and recreate it as needed, providing storage of objects as well as data exchange.By using Serailizaton,we can send the object to a remote application by means of web service,passing an object from one domain to another be means of .net remoting,passing an object through firewall as an XML string or passing the user specific information across applications.

How do you use serailizataion:
Serialization is handled by classes and interfaces in the System.Runtime.Serialization namespace.you need to do two things to serialize an object.
1)a stream to contain the serialized objects
2)a formatter to serialize the objectds into the stream.

.NET serialization formats:
There are three fromats of serialization.
1) Binary Serialization : Light and compact used in Remoting
2) SOAP Serialization  : Interoperable use SOAP and  used in web Services
3) XML Serialization    :  Custom Serialization

SOAP and Binary Serialization:
Serialization is always needed when you transfer an object across a network.Both XML and Binary Serialization can serialize the entire object and all those object that are being refrenced by it.This is why it is also called Deep Serialization.SOAP sends it using HTTP Protocol which makes it most interoperable while Binary serialization is known for its light and compact nature. Web Services uses the SOAP Serialization and Remoting uses the Binary Serialization.If you want any class to serialize through any of these methods you should mark the class as [Serializable].

XML Serilization:
XML Serilization serialize only the public members.For XML Serialization,you need to use [Serializable] attribute and specify them for every public member which you to serialize.This is why it is also called Shallow Serialization.


Note : The  [NonSerialized] Attribute can be used to keep specific fields from being serialized.

Serialize an object with Binary Format (Binary Serialization Example) :
I am trying to give an example of Binary Serialization,which converts an employee object into stream(i saved it in a text file)  and recreating the object by using stream which is saved in text file.
Example:
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

namespace Serialization
{
    class Program
    {
        static void Main(string[] args)
        {
                 
            Employee emp = new Employee();
            string filename = @"C:\Serialization.txt";
            WriteToFile(emp,filename);
            ObjectFromFile(filename);
            Console.ReadLine();
        }

        public static void WriteToFile(Employee emp, String filename)
        {
            Stream stream = File.OpenWrite(filename);
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(stream, emp);
            stream.Close();
        }

        public static void ObjectFromFile(String filename)
        {
            Stream stream = File.OpenRead(filename);
            BinaryFormatter formatter = new BinaryFormatter();
            stream.Position = 0;
            object o = formatter.Deserialize(stream);
            stream.Close();
            Employee emp = (Employee)o;
            Console.WriteLine(emp.Empid + " " + emp.EmpName);
        }
    }

    [Serializable]
    class Employee
    {
        private int empid;
        private string empName;

        public int Empid
        {
            get
            {
                return empid;
            }
            set
            {
                this.empid = value;
            }
        }
        public string EmpName
        {
            get
            {
                return empName;
            }
            set
            {
                this.empName = value;
            }
        }
      
        public Employee()
        {
            empid = 1;
            empName = "Johny";
        }
    }
}

 output in console:
 1 Johny

I hope you can better understand what is a serialization in .NET and How to serialize an object and reconstruct the object by using Binary,SOAP serialization.


Method Overriding and Method Hiding [C#]


Method Overriding vs Method Hiding
Method Hiding is the concept of hiding the base class function from the derived class.We can create the complete new definition of base class function in derived class function.we can say hiding the base class function from derived class.Method Hiding can be achieved by using new keyword.
  public class Base 
        {
               public void Hello()
               {
                     

                   Console.WriteLine("Base Class");
               }
        }

        public class Derived : Base
        {
               public new void Hello()
               {

                   Console.WriteLine("Derived Class");
               }
         }
         public class TestHiding
         {

             public static void Main(string[] args)
             {

                  Derived  obj= new Derived ();                  

                  obj.Hello(); 
                  Console.ReadLine();
            }

         } 
 Output : Derived Class
 Method overriding means having two methods with same name and same siganture, one method in base class and other method in derived class.
   A subclass inherits methods from a base class. Sometimes, it is necessary for the subclass to modify the methods defined in the base class. This is referred to as method overriding.
   This can be achieved by using the virtual and override keywords. we have to use the virtual keyword for the method which in base class and override keyword  for the method in subclass.

   By default functions are not virtual in C# and so you need to write “virtual” explicitly.

   Class BaseClass
  {
    public virtual void hello()
    { Console.WriteLine(“Base Class”); }
  }

  Class SubClass : BaseClass
  {
    public override void hello()
   { Console.WriteLine(“SubClass”); }
  }

  static void main()
  {
    BaseClass objBase = new SubClass();
    objBase.hello();
  }

  //Output  ::: SubClass....

sealed keyword for methods | sealed methods [C#]

Sealed methods,how to use sealed methods

Yes. .NET allows the sealed methods.Sealed methods are used to define the overriding level of the virtual methods.Sealed keyword is always used with the override keyword.

 namespace sealedMethod_Example
 {
    class Program
    {
        public class Base
        {
            public virtual void Test()
            {
                Console.WriteLine("Base Method");
            }
        }

       public class Derived : Base
        {

           // Now the Test() has been sealed and can't be overridden
            public override sealed void Test()
            {
                Console.WriteLine("Derived Class Sealed method");
            }
        }
       //public class ThirdClass : Derived
       //{
       //    public override void Test()
       //    {
                 //Here we are trying to override the Test(),but it's not possible becasue we have been sealed Test() in Derived Class So it will give error.
       //    }
       //}

        static void Main(string[] args)
        {
            Derived d = new Derived();
            d.Display();
         }
       }
   }
 

sealed classes,sealed methods in C#

Sealed class is like the normal class but the sealed class can't inherited but can be instantiated like normal class.To declare sealed class we should use the sealed keyword with the class declaration.The sealed classes are useful inorder to protect our classes not to be used by any other classes.

Syntax :

    sealed class Employee
    {
        protected string ename;
    }

out and ref parameters for void method [C#]


 Yes we can use the out parameter for method type of void.it won't give any compilation errors.Because it out and ref parameters doesn't depend on return type of the method.

Return multiple values from the function


We can return multiple values from the function by using out parameters.
   
    The out parameters are used to return values in the same variables, that you pass an an argument of a method.out parameters are very useful when your method needs to return more than one values.

    Example:

    using System;
    class SomeName
    {
        public static void Main(String [] args)
        {
           int a,b=0;
           b=ParamTest(out a);
           Console.WriteLine("a = {0}", a);
           Console.WriteLine("b = {0}", b);
         }
        public static int ParamTest(out int a)
        {
            a=200;
            return 10;
        }
    }

   output :  a=200 b=10;

Return the identity value for an inserted row in SQL SERVER

We have several statements for returning the identity value for an inserted row.
  
1)scope_identity()
2)ident_current
3)@@identity

1) scope_identity() will return the last identity inserted in the current scope and session.
2)ident_current('Table Name') returns the last value inserted into that table on any connection. Remember to put the table name in quotes
3)@@identity will return the last identity value inserted in any scope.

Different types of transaction in SQL SERVER

There are three types of transactions.
    1)Auto commit transaction
    2)Implicit transaction
    3)Explicit transaction

1)Auto commit transaction :  This is the default transaction mode in sql server.Every SQL statement in sql server is either committed or rolled back. If it completes successfully it is committed else it is rolled back.
2)Implicit transaction : A new transaction is starts automatically when the current transaction is committed or rolled back.No need to define the start of the transaction. It generates continues chain of transactions.
3)Explicit transaction : ransactions that have a START and END explicitly written are called as an explicit transaction. They last only for the duration of the transaction.

@@ERROR variable in SQL SERVER 2005

The @@ERROR automatic variable is used to implement error handling code. @@ERROR variable contains the error ID which is produced by the last SQL statement executed during a client's connection. When a statement executes successfully, @@ERROR set to 0.

Transactions in SQL SERVER 2005

Transactions are a gruop of tasks into a single execution unit. Each transaction begins with a specific task and ends when all the tasks in the group successfully complete.So Transaction has only two results : success or failure.If all the tasks in a group are successful then the transaction is success.If any of the task in a group fails then the transaction fails.
    Users can group two or more SQL statements into a single transaction using the following statements:
    Begin Transaction
    Rollback Transaction
    Commit Transaction

    Syntax:

    BEGIN TRAN
    UPDATE  Employee  SET emp_firstname = 'John'  WHERE emp_id = 1
    IF @@ERROR <> 0
    BEGIN
         ROLLBACK TRAN
         return 11
   END
   COMMIT TRAN

   If the statement failed (i.e. @@ERROR <> 0) then we rollback the work performed so far and use the RETURN statement to exit the stored procedure.

How can we view all the triggers in a table

By Using sp_helptrigger sytax we can view all the triggers in a table.
sp_helptrigger Table_Name,it will list all the triggers present in a table

Is it possible to disable perticular trigger on a table?

Yes,we can disable particular trigger on a table.
ALTER TABLE Table_Name DISABLE TRIGGER trgAfter /*trgAfter is a trigger name*/

Can we disable all the triggers on particular table

Yes, we can disabled/enabled all the triggers for a specific table.
ALTER TABLE Table_Name [ENABLE|DISBALE] TRIGGER ALL

Instead Of Triggers in SQL SERVER 2005 and it's Syntax

Instead of trigger executes the code inside of the trigger instead of an Insert/delete/update commands.But we can write a code to insert/delete/update row inside the trigger.
    Instead of Triggers can be classified into 3 types.
    1.INSTEAD Of INSERT Trigger
    2.INSTEAD Of UPDATE Trigger
    3.INSTEAD Of DELETE Trigger

    Syntax:
    CREATE TRIGGER trgInsteadOf  ON [dbo].[Table_Name]
    INSTEAD OF DELETE /*Here we can use UPDATE or DELETE also for  INSTEAD OF UPDATE and INSTEAD OF DELETE Triggers*/
    AS
     -- write sole logic
    PRINT 'Instead Of Trigger fired.'
    GO

After Triggers in SQL SERVER 2005 and After Trigger Syntax

After Triggers run after an insert, delete and update.Views are not supported After Triggers.
    After Triggers can be classified into 3 types.
    1.AFTER INSERT Trigger
    2.AFTER UPDATE Trigger
    3.AFTER DELETE Trigger
   
    Syntax : AFTER INSERT Trigger
    CREATE TRIGGER trgAfter ON [dbo].[Table_Name]
    FOR INSERT /*Here we can use UPDATE or DELETE also for AFTER UPDATE and AFTER DELETE Triggers*/
    AS
                 -- write some logic
    PRINT 'AFTER Trigger fired.'
    GO

Triggers in SQL SERVER and Types of Trigges in SQL SERVER

Triggers are special types of Stored Procedures that are defined to execute automatically in place of or after data modifications. They can be executed automatically on the INSERT, DELETE and UPDATE commands on a table.we can't explicitly execute triggers.
    There are two types of triggers
    1)After Trigger
    2)Instead of Trigger

refer types of triggers in detail
After Triggers in SQL SERVER 2005 and After Trigger Syntax
Instead Of Triggers in SQL SERVER 2005 and it's Syntax

Difference between function and stored porcedure in SQL SERVER

The main differences between functions and stored procedures are
    1)Functions can be used in SQL Queries where as stored procedures can't be used in SQL queries.
    2)Stored procedure can run independently. It can be executed using EXECUTE or EXEC command where as  function cannot run independently.
    3)stored procedures has both in and out parameters,but the function takes only in parameters.
    4)A FUNCTION is always returns a value using the return statement. A  PROCEDURE may return one or more values through parameters or may not return at all
    5)Functions are normally used for computations where as procedures are normally used for executing business logic.
    6)Stored procedure is precompiled execution plan where as functions are not.

Advantage of stored procedure over query in SQL SERVER 2005

Stored procedure are precompiled and executed directly and it may contian block of SQL statements.
When client sends to request to execute query,every time it will compile first and executes the query.

Stored procedure in SQL SERVER and Advantage of using stored procedure in SQL SERVER

Stored procedure is a database object which contains one or more T-SQL statements that are stored in database.To use the stored procedure you send a request for it to be executed. When server recieves the request, it executes the stored procedure.
Adavantages:
    Stored procedures improve the database performance because stored procedures are pre-compiled and executes directly when client sends the request to execute the procedure.
   
   Syntax:
  
   CREATE PROCEDURE spVendorByState
          @VendorState varchar(50)
   AS
   BEGIN
          SELECT * FROM Table
    END
    GO

Difference between UNION and UNION ALL Commands

UNION : UNION Command is used to select the related information from two tables.When using the UNION command , the selected columns need to be of same datataype.with UNION Command only the distinct values are selected.
UNION ALL : UNION ALL Command is equal to the UNION Command except the UNION ALL select all the values.
   
    ex:
       
    Table1  
       
         id    rank
         1    First
         2    Second
         3    Third
         4    Fourth

    Table2  
       
         id    rank
         1    First
         2    Second
         3    Seventh
         4    Tenth

     UNION:
     select rank from Table1  UNION select rank from table2

      result:

          First
          Second
          Third
          Fourth
          Seventh
          Tenth

     UNION ALL:
     select rank from Table1  UNION ALL select rank from table2

     result:

             First
             Second
             Third
             Fourth
             First
             Second
             Seventh
             Tenth


SELF JOIN Example and scenario in SQL SERVER 2005

A self-join is a query in which a table is joined to itself.Self-joins are used to compare values in a column with other values in the same column in the same table.
    ex:
----------------------------------------------------
    empID    Name         ManagerID
----------------------------------------------------
       1           John         NULL       
       2           Steve          1       
       3           Billgates     1       
       4          Ozzy            2
       5          Homer         3
-----------------------------------------------------

       if we want to display all the employees with their Managers names.In this scenario we can use self-join      

CROSS JOIN Example in SQL SERVER 2005

CROSS-JOIN is a Cartesian join that does not necessitate any condition to join.The resultset contains records that are multiplication of record number from both the tables.suppose if we have 10 records in table A and 5 records in table B,it will return 50(10*5) records.
   
     Ex:
     Left Table(emp Table)

         --------------------------------
    empID    FirstName   
         --------------------------------
       1    John        
       2    Steve        
        ---------------------------------

     Right Table(dept Table)

         ------------------------------------------------------
    empID        DeptName
         ------------------------------------------------------
    1        IT
    2        Networking
         ------------------------------------------------------

     Query:
         SELECT * FROM emp AS e FULL JOIN dept AS d
       
     Result:

           empID     FirstName        IndividualId    AccessLevel
            1              John                             1           IT
            1              John                             2           Networking
            2              Steve                           1           IT
            2              Steve                           2           Networking
   
  

FULL OUTER JOIN Example in SQL SERVER 2005

A FULL OUTER JOIN Join combines Left outer join and right outer join.it will display the rows from either tables when the condtions are met and returns null when there is no match found.
   
     Ex:
     Left Table(emp Table)

  ------------------------------------------------------------------------
    empID    FirstName    LastName    UserName
   ------------------------------------------------------------------------
       1             John          Miller                 John
       2             Steve         Jobs                    Steve
       3           Billgates     john                    Billgates
       4           Ozzy         Ozzbourne           Ozzy
       5           Homer         Gain                   Homer
        --------------------------------------------------------------------------

     Right Table(dept Table)

 ------------------------------------------------------
    empID        DeptName
  ------------------------------------------------------
    1        IT
    2        Networking
    3        Networking
    4        Networking
    12        Admin
 ------------------------------------------------------

     Query :
    
     SELECT * FROM emp AS e
     FULL JOIN dept AS d
     ON e.empid = d.empid

    result:

    empID     FirstName    LastName        UserName    IndividualId    AccessLevel
        1               John             Miller              John                 1                     IT
        2               Steve           Jobs                 Steve                2              Networking
        3            Billgates         john                 Billgates          3              Networking
        4             Ozzy             Ozzbourne       Ozzy                4              Networking
        5            Homer            Gain                Homer        NULL           NULL
    NULL       NULL             NULL               NULL           12             Admin

RIGHT OUTER JOIN Example in SQL SERVER

This join returns all the rows from the right table with the matching rows from the left table. If there are no columns mathcing in the left table ,it returns NULL values.
    Use Right Outer Join when you only want to return rows that have matching data in the right table, even if there's no matching rows in the left table.

Ex:

     Left Table(emp Table)


    ------------------------------------------------------------------------
    empID    FirstName    LastName    UserName
    ------------------------------------------------------------------------
       1               John         Miller        John
       2               Steve         Jobs        Steve
       3          Billgates         john        Billgates
       4            Ozzy         Ozzbourne    Ozzy
       5            Homer         Gain             Homer
   --------------------------------------------------------------------------

     Right Table(dept Table)

  ------------------------------------------------------
    empID        DeptName
  ------------------------------------------------------
    1        IT
    2        Networking
    3        Networking
    4        Networking
    12        Admin
   ------------------------------------------------------
    
     Query :

     SELECT * FROM emp AS e
     RIGHT JOIN dept AS d
     ON e.empid = d.empid

    result:

    empID     FirstName    LastName        UserName    IndividualId    AccessLevel
        1            John             Miller                 John                1                      IT
        2            Steve             Jobs                  Steve               2        Networking
        3          Billgates         john                Billgates            3        Networking
        4           Ozzy             Ozzbourne           Ozzy             4        Networking
     NULL       NULL        NULL                    NULL         12        Admin

LEFT OUTER JOIN Example in SQL SERVER 2005

This join returns all the rows from the left table with the matching rows from the right table. If there are no columns matching in the right table, it returns NULL values.

Use this when you only want to return rows that have matching data in the left table, even if there's no matching rows in the right table.
     Ex:

     Left Table(emp Table)

         ------------------------------------------------------------------------
         empID    FirstName    LastName    UserName
         ------------------------------------------------------------------------
              1             John         Miller             John
              2             Steve        Jobs              Steve
              3          Billgates      john              Billgates
              4             Ozzy         Ozzbourne    Ozzy
              5            Homer        Gain             Homer
        --------------------------------------------------------------------------

     Right Table(dept Table)

         ------------------------------------------------------
            empID        DeptName
         ------------------------------------------------------
               1                  IT
               2          Networking
               3          Networking
               4          Networking
              12          Admin
         ------------------------------------------------------
    
     Query:

     SELECT * FROM emp AS e
     LEFT JOIN dept AS d
     ON e.empid = d.empid

    result:

    empID     FirstName    LastName        UserName    IndividualId    AccessLevel
        1             John             Miller                 John                 1                     IT
        2             Steve           Jobs                    Steve                2             Networking
        3             Billgates      john                    Billgates          3             Networking
        4             Ozzy           Ozzbourne          Ozzy                4             Networking
        5             Homer        Gain                    Homer        NULL          NULL
     

INNER JOIN Example in SQL SERVER

INNER JOIN returns rows when there is atleast one match in both tables.This is the default JOIN in Sql Server.

Example:
Suppose if we have two tables emp and dept(for ease of understanding).

         empID   empName
             1           John
             2           Bush
             3           Scoutt
    
         deptID  empID    deptName
             1            1           IT
             2            2           Networking
             3            3           Admin

      SELECT e.empName,d.deptName FROM emp AS e
                  JOIN dept d ON e.empID = d.empID   
       
    Results:
    --------------------------
    John    IT
    Bush    Networking
    Scoutt    Admin
    --------------------------

    We can also use the where condition to get the desired output.
      
    SELECT e.empName,d.deptName FROM emp e
                  JOIN dept d ON e.empID = d.empID   
                  WHERE d.deptName = 'IT'

    Results:
    ---------------
    John    IT
    ---------------


JOINS in SQL SERVER and Different types of JOINS in SQL Server

JOINs allows the retrieval of data records from one or more tables having some realrion between them.
There are 3 types of JOINS in sql server.
1)INNER JOIN
2)OUTER JOIN
    a)LEFT OUTER JOIN
    b)RIGHT OUTER JOIN
    c)FULL OUTER JOIN
3)CROSS JOIN

Refer the Example :
INNER JOIN Example in SQL SERVER
LEFT OUTER JOIN Example in SQL SERVER 2005
RIGHT OUTER JOIN Example in SQL SERVER 2005
FULL OUTER JOIN Example in SQL SERVER 2005
CROSS JOIN Example in SQL SERVER 2005
SELF JOIN Example and scenario in SQL SERVER 2005



Difference between unique key and primary key

Differences:
1)Both primary key and unique key enforces Uniqueness
2)primary key doesn't allow any one NULL value,where the unique allow one NULL value. If the unique key is defined in a combination of fields, then every field can accept NULL and can have some values on them, as long as the combination values is unique.
3)we can create only one primary key on a table,but we can create more than one unique key on a table.
4)By default primary key creates clustered index where as unique key creates non-clustered index.

What is a constraint in Sql Server and explain different types of constraints?

Constraints are allows us to enforce rules in our database. Sql Server support 6 types of constraints.

    PRIMARY KEY constraint is a unique identifier for a row within a database table. Every table should have a primary key constraint to uniquely identify each row. The primary key constraints are used to enforce entity integrity(refer RDBMS FAQ's).

    UNIQUE constraint enforces the uniqueness of the values in a set of columns, so no duplicate values are entered. The unique key constraints are used to enforce entity integrity as the primary key constraints.

    FOREIGN KEY constraints are fields in a relational database table that match the primary key column of another table. Foreign keys can be used to cross-reference tables.

    CHECK constraint is used to limit the values that can be placed in a column. The check constraints are used to enforce domain integrity.

    NOT NULL constraint enforces that the column will not accept null values. The not null constraints are used to enforce domain integrity, as the check constraints.

    DEFAULT constraints allow you to specify a value that the database will use to populate fields that are left blank in the input source.


different types of relationships


There are 3 types of relationships.
1)one-one
2)one-many
3)many-many

    one-one relationship means,when there is eactly one record in table 1 that corresponds to exactly one record in table 2.
   
    one-many relationship means,when there is eactly one record in table 1 that may have many linked records table 2,But each record in Table 2 must have only one corresponding records in Table 1.

    many-many relationship means,when one record in table 1 that may have many linked records table 2 and vice-verca.


Advantages And Dis-Advantages of Normalization


Advantages:
1)Smaller database: By eliminating duplicate data, you will be able to reduce the overall size of the database.
2)Better performance:
a. Narrow tables: Having more fine-tuned tables allows your tables to have less columns and allows you to fit more records per data page.
b. Fewer indexes per table mean faster maintenance tasks such as index rebuilds.
c. Only join tables that you need.
Disadvantages:
1)More tables to join: By spreading out your data into more tables, you increase the need to join tables.
2)Tables contain codes instead of real data: Repeated data is stored as codes rather than meaningful data. Therefore, there is always a need to go to the lookup table for the value.
3) Data model is difficult to query against: The data model is optimized for applications, not for ad hoc querying.

De-normalization in RDBMS

De-normalization is the process of attempting to optimize the performance of a database by adding  redundant data.

Normalization in RDBMS

The process of organizing data  to minimize  redundancy  is  called normalization. Normalization usually  involves  dividing  a  database  into  two  or  more  tables  and  defining  relationships between  the  tables.  The  objective  is  to  isolate  data  so  that  additions,  deletions,  and modifications of a field can be made in just one table and then propagated through the rest of the database via the defined relationships.

User-Defined Integrity in RDBMS


User-defined integrity allows you to define specific business rules that
Do not fall into one of the other integrity categories.

Referential Integrity in RDBMS


Referential integrity maintains the defined relationships between tables when records are entered or deleted.In SQL Server,referential integrity is based on relationships between foreign keys and primary keys/Unique keys(through FOREIGN KEY and CHECK constraints).
When you enforce referential integrity, SQL Server prevents users from:
1) Adding records to a related table if there is no associated record in the primary table.
2) Changing values in a primary table that result in orphaned records in a related table.
3) Deleting records from a primary table if there are matching related records.
For example, if we have emp and dept tables in our database,the referential integrity is based on the relationship between the foreign key (dept_id) in the emp table and the primary key (dept_id) in the dept table.

Domain Integrity in RDBMS


Domain integrity is the validity of entries for a given column. You can enforce domain integrity by restricting the type (through data types), the format (through CHECK constraints and rules), or the range of possible values (through FOREIGN KEY constraints, CHECK constraints, DEFAULT definitions, NOT NULL definitions, and rules).
Example, if we have an emp_rating column which is intended to have values ranging from 1 to 10,the database should not allow the value except from 0-10.

Entity Integrity in RDBMS


Entity integrity defines a row as a unique entity for a particular table.We can enforce the Entity Integrity through the indexes, UNIQUE constraints, PRIMARY KEY constraints, or IDENTITY properties.
Example,if we entered the emp_id is 1 in a table,the database should not allow other emp_id with the same value of 1.

Data Integrity and its categories


Enforcing data integrity ensures the quality of the data in the database.For example
    if we entered the emp_id is 1 in a table,the database should not allow other emp_id with the same value of 1.
    if we have an emp_rating column which is intended to have values ranging from 1 to 10,the database should not allow the value except from 1 to 10.
    if we have dept_id column which stores department number for the employee,the database should allow valid department number.
Data Integrity falls into 4 categories.
1)Entity Integrity
2)Domain Integrity
3)Referential Integrity
4) User-defined integrity

Properties of the Relational tables?


Relational tables have six properties:

Values are atomic.
Column values are of the same kind.
Each row is unique.
The sequence of columns is insignificant.
The sequence of rows is insignificant.
Each column must have a unique name.

What is RDBMS?


Relational  Data  Base Management  Systems  (RDBMS)  are  database management  systems that  maintain  data  records  and  indices  in  tables.  Relationships  may  be  created  and maintained  across  and  among  the data  and  tables.  In  a  relational database,  relationships between  data  items  are  expressed  by means  of  tables.
    An  RDBMS  has  the  capability  to  recombine  the  data items  from different files, providing powerful tools for data usage.

What is Database?


A database is a collection of information that is organized so that it can easily be accessed, managed, and updated.
Databases are sometimes classified according to their organizational approach.
The most prevalent approach is the relational database, a tabular database in which data is defined so that it can be reorganized and accessed in a number of different ways.
A distributed database is one that can be dispersed or replicated among different points in a network.
An object-oriented programming database is one that is congruent with the data defined in object classes and subclasses.

Enterprise library in .NET

Enterprise Library is a collection of application blocks(please refer What are application blocks and it's types?) intended for use by developers who build complex, enterprise-level applications.

Refer Application blocks in .NET and types 

Application blocks in .NET and types


Application blocks are a set of classes and methods for doing a specific task(like data access, security, logging, exception handling and others) written by Microsoft patterns and Practices team.Application Blocks can be freely used and customized by the developers for their own purpose.
There are following application blocks are available:
    1)Data Access application block
    2)Logging Application Block
    3)Exception Handling application block
    4)Caching application block
    5)User Interface Process application block
    6)Aggregation application block
    7)Configuration Management application block
    8)Asynchronous Invocation application block

Difference between generic collections and non-generic collections


Generic collections can hold same type of data and we can decide while initializing what type of data that collections can hold.Non generic collections hold elements of different data types.
Generic collections reduced overhead of implicit and explicit conversions(because while initailing , will decide what type of data that collections can hold ). Non-generic collections include implicit and explicit conversions that means every data type will convert to and from object.So Generic collections give the best performance than non-generic collections.
    Generic collections are Type Safe and secure.
   
    examples of Generic collections are List , Dictionary etc.
    List<double> list = new List<double>();
   
    examples of non-Generic collections are ArrayList and Hash tables
    ArrayList arr = new ArrayList();

Generic classes in C#


Generic classes allows us to implement the functionality as like normal classes,but the object types will be passed to the methods at the point of use. examples of Generic classes are List , Dictionary etc.
Syntax :
List<double> list = new List<double>(); //we have to specify the object type at the declaration

Nullable Types in C#


The primitive Data Types in C# (like int,double,float,bool etc) will not accept the null values.To make these primitive data types accept null values we will use the Nullable Types.Nullable data types can represent all the values of an underlying type plus an additional null value.
When there are hundreds of values for a perticular column in a database table,there are chances that some of the values might have null in it.In those scenarios ,instead of checking against null value ,we can directly assign into the primitive data types.
Nullable types are instances of the struct System.Nullable<T> where T can hold any primitive data type. Nullable types can be declared in two different ways
    1)Nullable<int> i = null;
    2)int? j= 10;
 
    The nullable type in C# has two properties namely HasValue and Value.
    HasValue :  If the nullable type variable holds a definite value then this property returns True. If the nullable type variable holds null value then HasValue property returns False.
    Value:  It returns value of the nullable type.

Dynamic loading of an assembly


The Assembly class provides some methods to load an assembly at runtime.
    1)Load() : This is the static overloaded method which takes the assembly name as input parameter and searches the given assembly name in the system.
    2)LoadFrom() : This is the static overloaded method which takes the complete path of an assembly and searches at the specified location instead of searching in the system.
    3)GetExecutingAssembly() : This method is used to obtain the currently running assembly information.it doesn't have any parameters.
    4)GetTypes() :  This is used to obtain the details of all the types that are defined in the corresponding assembly.
    5)GetCustomAttributes() : This static overloaded method gets the attributes attached to the assembly.

    Sample:
   
     Assembly objAss;

    //must supply a valid fully qualified assembly name here.
    objAss = Assembly.Load("mscorlib,2.0.0.0,Neutral,b77a5c561934e089");

    // Loads an assembly using its file name  
    //objAssembly = Assembly.LoadFrom(@"D:\test.exe");

    //this loads currnly running process assembly
    // objAssembly = Assembly.GetExecutingAssembly();

    Type[] Types = objAss.GetTypes();

    //Display all the types contained in the specified assembly.
    foreach (Type objType in Types)
    {
          Console.WriteLine(objType.Name.ToString());
    }

Which Namespace will be used for reflection?


We can access the metadata information from an assembly using .NET Reflection.
System.Reflection and System.Type class plays a very important role in .NET Reflection.

What is Profile Properties in .net?


ASP.NET provides a feature called profile properties, which allows you to store user-specific data. This feature is similar to session state, except that the profile data is not lost when a user's session expires. The profile-properties feature uses an ASP.NET profile, which is stored in a persistent format and associated with an individual user. The ASP.NET profile allows you to easily manage user information without requiring you to create and maintain your own database. In addition, the profile makes the user information available using a strongly typed API that you can access from anywhere in your application. You can store objects of any type in the profile. The ASP.NET profile feature provides a generic storage system that allows you to define and maintain almost any kind of data while still making the data available in a type-safe manner.
    To use profile properties, you must configure a profile provider. ASP.NET includes a SqlProfileProvider class that allows you to store profile data in a SQL database, but you can also create your own profile provider class that stores profile data in a custom format and to a custom storage mechanism such as an XML file, or even to a web service.
    Because data that is placed in profile properties is not stored in application memory, it is preserved through Internet Information Services (IIS) restarts and worker-process restarts without losing data. Additionally, profile properties can be persisted across multiple processes such as in a Web farm or a Web garden.

Difference between Application and Cache objects?


Both the cache and application objects are global to entire applications.but the difference is the usage.
    cache will used for frequently changed items.application object is for the items which doesn't change frequently.
    Items in the cache will be removed automatically because it has the expiration time. but application object doesn't have the expiration date it will avail for entire life of the application.

Main Difference is while accessing the application data we need to explicitly Lock the variable and release the Lock once used,But in case of Cache this synchronization will be done implicitly.

What is cache dependency?what are the different types of cache dependency in .net?


Cache Dependency means that an item can be removed from the cache when a dependent entity gets changed.
    There are 2 types of cache dependencyies.
    1)File dependency
    2)Key dependency

    File dependency
        This provides an option to remove an item automatically from the cache whenever a disk file changes.
        Syntax:
                  object Data;
                  //Load Data from errorList.xml
                  CacheDependency fileDependency =  new CacheDependency(Server.MapPath("errorList.xml"));
                  Cache.Insert("ERROR_LIST", Data, fileDependency);
      when ever the errorList.xml has changed,EROR_LIST item will be removed from cache automatically.
   
   Key dependency
        Key dependency is similar to file dependency and it dependent on another item in the cache and gets invalidated when the dependent item gets changed or removed.

What are absoluteExpiration and slidingExpiration parmeters of the Insert and Add methods?


SlidingExpiration
        A TimeSpan object that identifies how long the data should remain in the cache after the data was last accessed.
        If you’re using absolute expiration, specify Cache.NoSlidingExpiration for this parameter.
AbsoluteExpiration
        A DateTime object that identifies when the data should be removed from the cache.
        If you’re using sliding expiration, specify Cache.NoAbsoluteExpiration for this parameter.

How do you implement Data Caching in ASP.NET?


Data caching is carried out manually in your code.In data caching,you store important pieces of information that are time consuming to reconstruct such as dataset retreived from a database.
    ASP.NET Provides 3 methods to store data or objects into the cache.

    Adding :  
    Cache["Item"] = "Some string data";
    Cache.Add("Item", "Some data", null, Cache.NoAbsoluteExpiration, System.TimeSpan.FromMinutes(1),            CacheItemPriority.Default, null);
    Cache.Insert("Item", "Some data");

    Getting:
          if(Cache["Item"] != null)
String str = Cache["Item"] .ToString();

    Remove:
          Cache.Remove("Item");

Is cache object available for all web forms with in a web application?

Yes, the Cache object is global,means data stored in the Cache object is available anywhere within a Web application. In this way, the Cache object is very similar to the intrinsic Application object.

Fragment caching in ASP.NET?

Instead of caching the complete page, some portion of the rendered html page is cached. E.g.: User Control used into the page is cached and so it doesn’t get loaded every time the page is rendered. 

What is Output caching and how do you implement in asp.net?


This is the simplest type of caching.It stores a copy of finally rendered html page that is sent to the client.When the next time,the client rquests this page again, the stored copy is sent to the client instead of parsing the entire page again.
In oreder to implement the Output caching, we need to specify an @OutputCache directive at the top of the page.
   
    The syntax is as shown below:
         <%@ OutputCache Duration=5 VaryByParam="None" %>
    Duration: The time in seconds of how long the output should be cached.After the specified time elapsed,the cache will be removed and page content generated for the next request and this will be stored for next 5 sec.
    VaryByParam: cache will be vary on parameters that you passed in the query string.
    I have set the VaryByParam="None" in above syntax,it will cache the finally rendered html into the cache regardless of the paramerts you have passed in the query string.
   
    suppose if you are requseting the page ..test.aspx?id=1,you can put the id in your VaryByParam like this
    VaryByParam="id"  

Caching in asp.net? Types of Caching in ASP.NET?


Caching could provide the performance improvment of the web application by retaining important data for just a short period of time.
ASP.NET supports three types of caching for Web-based applications:
1)Output Caching
2)Data Caching


Difference between Session Object and Application Object?


Session object is used to store state specific information per client basis. It is specific to particular user.
Application object is used to store data which available across the entire application and shared across multiple users sessions.
 
Session has the expiration time,default time 20 mints.But application object doesn't have the expiration time.
   
Session object is used to maintain the session of each user. If one user enter in to the application then they get session id if he leaves from the application then the session id is deleted.If they again enter in to the application they get different session id.
But for application object the id is maintained for whole application.it doesn't differ for any user.




Different types of mode in session?


You can store session's data in 3 different ways.

     1)Inproc (In-Process Mode):
         This Method is most common and default method to store session specific information.This mode is best fit for small applications which can be host on a single server.
         Session information/data stored in memory of local web server(aspnet_wp.exe).
         Syntax:
                 <sessionState mode = "inproc"
          cookieless = "true|false"
                    timeout = "20" />
        This mode will be faster than the other 2 modes (StateServer and SqlServer) But Session data will be lost if the worker process or application domain recycles.

    2)State Server Mode:
        This mode is suitable for scalable and highly available applications.
        In this mode , sessions are serialized and stored in memory in a separate process aspnet_state.exe.  State Server can run on another machine.

        Syntax:
                         <sessionState mode="StateServer"
                            StateConnectionString="tcpip=127.0.0.1:42424"
                            cookieless="false" timeout="20"/>
    3)SQLServer Mode:
        In this Mode, sessions are serialized and stored in SQL server.
       
        Syntax:
<sessionState mode="SQLServer"
                    sqlConnectionString="data source=server;user id=userid;password=pwd"
                    cookieless="false" timeout="20" />

Session Objects in ASP.NET?


Session object is used to store state specific information per client basis. It is specific to particular user.Session data persists for the duration of user session.
You can disable session for a page using EnableSessionState attribute.
 <%@ Page EnableSessionState = "False" %>
You can set off session for entire application by setting mode=off in web.config file to reduce overhead for the entire application.
   
    web.config file sysntax for session:
   
    <sessionState mode = "off|inproc|sqlserver|stateserver"
       cookieless = "true|false"
       timeout = <Timeout in Minutes,default 20 mints>
       sqlconnectionstring = <SQL connection string,only required when mode=SQLServer>
       server = <The server name ,only required when the mode is State Server>
       port = <The port number, only required when the mode is State Server>      
    />

what is Application Object?


Application object is used to store data which available across the entire application and shared across multiple users sessions.
Data which needs to be persisted for entire life of application should be stored in application object.
It's a great place to store data which changes infrequently.

 syntax:

Application.Lock();
Application["cnt"]="count";
        To remove the application variable cnt from the application state, we need to write
        Application.Remove("cnt");
        If we want to remove all variable for application state we need to write
        Application.RemoveAll();
Application.UnLock();

How do you implement the control state?


Implementation of Control state is easy.
1)Override the OnInit method of the control and add the call for the Page.RegisterRequiresControlState method with the instance of the control to register.
2)Override the  LoadControlState and SaveControlState in order to save the required state information.

Example:

      public class ControlStateCustomWebControl : Control
      {
          private string stateToSave;
       
         protected override void OnInit(EventArgs e)
         {
             Page.RegisterRequiresControlState(this);
             base.OnInit(e);
         }

        protected override object SaveControlState()
        {
            return stateToSave;
        }

        protected override void LoadControlState(object state)
        {
           if (state != null)
          {
              stateToSave = state.ToString();
          }
        }

    }

Control state in ASP.NET?

The control state allows us to save a control’s state information when the EnableViewState property is turned off. Unlike ViewState a developer can’t turn off control state. The control state can be implemented only in controls that you implement (should be used for custom controls).

What is Query String?


Query strings are usually used to send information from one page to another page like aspx?id=10.Most browsers impose a limit of 255 characters on URL length.

Very simple to pass the values from one page to another but these values are clearly visible in the browser.

we can access the Query String value as
string id;
id=Request.Params["id"];

Difference between view state and a hidden field?


HiddenFeilds are used to store small amout of data during the post backs.Hidden field stores a single variable in its value property and must be explicitly added it to the page.
Each control on a Web Forms page, including the page itself, has a ViewState property, it is a built-in struture for automatic retention of page and control state, which means you don’t need to do anything about getting back the data of controls after posting page to the server.
Unlike Hidden Field, the values in ViewState are invisible when ‘view source’, they are compressed and encoded.
Hidden Fields contain information that is not visible on the page but is posted to the server along with a page post back While View State is the mechanism that asp.net uses to maintain the state of controls across page post backs.
Hidden Fields are used for pages that post to themselves or to other pages while View State works only when a page posts back to itself.
Hidden Fields does not support for storing structured values while View State support for structured values.

Explian about the view state?


View State is a built in feature in web controls to persist data between page post backs.By default,Each control's of EnableViewState property will be set to true.so that we can disable the viewstate for the controls which we don't want to maintain state.
We can also disable View State for the entire page by adding EnableViewState=false to @page directive.View state data is encoded as binary Base64 - encoded which adds overhead to the page.This will be the disadvantage of the viewstate.

we can also store specfic data across the postbacks.

ex:
// Add item to ViewState
ViewState["state"]  = someValue;
//Reading items from ViewState
Response.Write(ViewState["state"]);

What is Hiddenfield and what are advantages and disadvantages of Hiddenfield?


Hidden fields are used to store data at the page level. These fields are not rendered by the browser. It's just like a standard control for which you can set its properties. Whenever a page is submitted to server, hidden fields values are also posted to server along with other controls on the page.

Ex:
//To Set Value
Hidden1.Value="Set Value Here";
//to retrieve a value
string strGetValue = Hidden1.Value;

Simple to implement and store small amout of data so they take less size.
These won't fit for sensitive data and values can be clearly visisble when passing through the network.

What is cookie and cookie advantages and disadvantages?


A cookie is a small piece of text stored on user's computer in the form of name-value pair.Cookies are used by websites to keep track of visitors. Every time a user visits a website, cookies are retrieved from user machine and help to identify the user.

Example:

Get the Cookie Value:
       if (Request.Cookies["Name"] != null)
           String StrName = Request.Cookies["Name"].Value;
Set the Cookie Value:
           Response.Cookies["Name"].Value= "username";

Cookies are very simple to use but cookies can be disabled on user browsers and cookies will not fit for sensitive data.

Different state management techniques in asp.net?


Web applications are based on stateless HTTP protocol which does not retain any information about user requests. In typical client/server communication using HTTP protocol, page is created each time when the page is requested. So ASP.NET provides two types of state management options.They are

1.Client side state management options
    Cookies
    QueryStrings (URL)
    Hidden fields
    View State
    Control state (ASP.NET 2.0)

2.Server side state management options
    Application
    Session
    Cache
    Profile Properties

What is reflection?

Reflection is the process of getting the metadata information from assemblies..NET Reflection allows an application to collect information about itself and also to manipulate on itself. It can be used to find all types in an assembly and/or dynamically invoke methods in an assembly. This includes information about the type, properties, methods, and events of an object. With Reflection, we can dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties.

Difference between namespace and assembly?

A namespace is just a grouping of related classes. It's a method of putting classes inside a container so that they can be clearly distinguished from other classes with the same name.The physical grouping is accomplished by an assembly, which equates most directly to a dynamic link library (DLL), COM object, or OCX module.
The .NET CLR contains multiple namespaces, which are spread across many assemblies. For example, ADO.NET is the set of classes located in the System.Data namespace, and ASP.NET is the set of classes located in the System.Web namespace.
In Visual Studio .NET, code is physically organized and structured in assemblies. An assembly is almost identical to a DLL, although one assembly consists of one or more DLL or EXEs.
one assembly can contain one or more namespaces, and one namespace can be contained by one or more assemblies. Each assembly can be configured with a root namespace. If the root namespace value is left blank, the root namespace value defaults to the assembly name.
 Differences:
 1)A namespace is logically groups classes.An assembly is physical grouping of logical units.
 2)An Assembly contains one or more namespaces.

Home

What is the procedure to deploy the shared assembly in GAC?

If we want to deploy the shared assembly we need to do the following things.
1)Create the Strong Name
2)Sign the project with SNK file.
3)Install the dll

Step 1 :
    Strong Name is only needed when you want to deploy the shared assembly in GAC.Strong Names helps GAC to differentiate between two versions. Strong names use public key cryptography which use public key and private key concept so that no one can spoof it.
Procedure for creating strong name:
    Goto Visual Studio Command Prompt from start menu.
    type this command [sn.exe -k "D:\test.snk"]
    then it will create the strong name key file.

Step 2 :
    Once you have created the sn key file,then go to your class library ,now Click on project -- properties the browse the SNK file[signing TAB] to the respective folder and compile the project.

Step 3 :
    Goto “Visual Studio Command Prompt” and type “gacutil –i (assembly_name)”, where (assembly_name) is the DLL name of the project.

Then the respective assembly will be deployed in the GAC.we can use this assembly in .net any application on the same machine by adding the web reference.

Home

What are different types of assembly?

There are 2 types of assembly.
1) Private assembly
2) Shared assembly
A Private assembly is normally used by one application and stored in application's directory.
A Shared assembly is used by more than one application and stored in GAC(Global assembly cache)
which is a repository of  assemblies maintained by the .NET runtime.

Home