Which protocol to use connecting to SQL Server

This connection string exemplifies how the network specification can look like inside the connection string.

"Provider=sqloledb;Data Source=190.190.200.100,1433;Network Library=DBMSSOCN;Initial Catalog=pubs;User ID=myUsername;Password=myPassword;" Network protocol codes
Name Network library
dbnmpntw Named Pipes
dbmslpcn Shared Memory (local machine connections only, might fail when moving to production...)
dbmssocn Winsock TCP/IP
dbmsspxn SPX/IPX
dbmsvinn Banyan Vines
dbmsrpcn Multi-Protocol (Windows RPC)
dbmsadsn Apple Talk
dbmsgnet VIA

Important note
When connecting through the SQLOLEDB provider use the syntax "Network Library=dbmssocn" and
when connecting through the MSDASQL provider use the syntax "Network=dbmssocn".

What is an Application Pool?

An Application Pool can contain one or more applications and allows us to configure a level of isolation between different Web applications.

Windows TCP Ports

Predefined Ports
IANA Categories of TCP and UDP Ports
Port Category Port Number Range Description
Well-known ports 0–1023 Typically used by standard system processes or programs that are executed by users with administrator credentials. Assigned by IANA.
Registered ports 1024–49151 Used by ordinary user processes or programs that are executed by ordinary users. IANA does not assign these ports, but registers use of them as a convenience for the TCP/IP community.
Dynamic or private ports 49152–65535 Unassigned and unregistered ports used for private applications, client-side processes, or other processes that dynamically allocate port numbers.

Some of the default TCP port numbers for processes that are commonly used
TCP Ports and Associated Services
Default TCP Port Number Internet Service
20 FTP Data Channel
21 FTP Control Channel
23 Telnet (enabled on some intranet or Internet servers)
25 Simple Mail Transfer Protocol (SMTP)
80 HTTP for World Wide Web
119 Network News Transfer Protocol (NNTP)
443 Hypertext Transfer Protocol over TLS/SSL (HTTPS) for secure World Wide Web
563 Network News Transfer Protocol over TLS/SSL (NNTPS)
For More Info : http://www.microsoft.com/smallbusiness/support/articles/ref_net_ports_ms_prod.mspx
http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers

Events order in SQL (Trigger/Constratin)

  • Identity Insert Check
  • Nullability constraint
  • Data type check
  • Instead of trigger
  • Primary key
  • Check constraint
  • Foreign key
  • DML Execution (update statements)
  • After Trigger

What is #, ##, @, @@ means in SQL?

  • @@ - System variables
  • @ - user defined variables
  • Local temporary table will be accessible to only current user session
  • Global temporary table will be accessible to all users

Finally Use

  • If you have an Exit Sub statement in your catch block. Normally this statement would exit the subroutine immediately, but in this situation the Finally Block is executed first.
  • In ASP.NET app and you have a Response.Redirect statement in your Catch block, once again the Finally Block would be called before the redirect happens.
  • If there is another error that happens within your Catch block code, normally it would be immediately raised to the calling code, but in this situation the Finally Block is called first.

What is VTable

(virtual function table) An ordered array containing pointers to virtual functions. Each object must also contain a pointer to its vtable; a pointer to this pointer is returned by QueryInterface.

Disable Browser Caching (ASP.NET)

Response.Cache.SetCacheability(HttpCacheability.NoCache)

What is Formatter

Formatter is the abstract (MustInherit in Visual Basic) base class for all runtime serialization formatters
  • SoapFormatter :  Serializes and deserializes an object, or an entire graph of connected objects, in SOAP format.
     
  • BinarryFormatter :  Serializes and deserializes an object, or an entire graph of connected objects, in binary format.

Singleton

Every incoming message is serviced by the same object instance. Singleton types never have more than one instance at any one time. If an instance exists, all client requests are serviced by that instance. If an instance does not exist, the server creates an instance and all subsequent client requests will be serviced by that instance.

Globalization & Localization

  • Globalization : Globalization is the process of designing and developing a software product that functions in multiple cultures/locales. Globalization is the process of designing and developing an application that supports localized user interfaces and regional data for users in multiple cultures.
  • Localization : Localization is the process of translating an application's resources into localized versions for each culture that the application will support

Application domain

An application domain (often AppDomain) is a virtual process that serves to isolate an application. All objects created within the same application scope are created within the same application domain. Multiple application domains can exist in a single operating system process, making them a lightweight means of application isolation.

What is reflection?

Refelction is the mechanism of discovering class information solely at run time. OR Assemblies contain modules, modules contain types, and types contain members. Reflection provides objects that encapsulate assemblies, modules, and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object.

All .NET compilers produce metadata about the types defined in the modules they produce. This metadata is packaged along with the module, and can be accessed by a mechanism called reflection. The System.Reflection namespace contains classes that can be used to interrogate the types for a module/assembly.

Reflection can also be used to dynamically invoke methods (see System.Type.InvokeMember), or even create types dynamically at run-time (see System.Reflection.Emit.TypeBuilder).

What is serialization & Deserialization ?

Serialization is the process of converting an object into a stream of bytes. Deserialization is the opposite process of creating an object from a stream of bytes.

Serialization/Deserialization is mostly used to transport objects (e.g. during remoting), or to persist objects (e.g. to a file or database).

The .NET Framework supports two general types of serialization: shallow and deep.

Shallow serialization is the process of converting the read-write property values of an object into a byte stream, and is the technique used by the XmlSerializer and Web Services. This is called shallow serialization, because it doesn't serialize the object's underlying data but only the data available through public read-write property methods.

Deep serialization is the process of converting the actual values stored in an object's variables into a byte stream. It is the technique used by the BinaryFormatter and SoapFormatter objects, and by .NET Remoting.

Why GC should control destructors why not us?

GC can do better object release than we can. If we do manual memory management one has to take care both allocation and de-allocation of memory. So there is always chance that one can forgot de-allocation. And also manual memory management is time consuming and complex process.

JIT compilers in CLR

  • Econo-JIT : This compiler has a very fast compilation time; but it produces un-optimized code - thus the program may start quickly but would run slow. This compiler is suitable for running scripts.
  • Standard-JIT: This compiler has a slow compilation time; but it produces highly optimized code. Most of the times CLR would use this compiler to run your IL code.

SQLClient NameSpace

The SQL Classes communicate with SQL Server directly on the level of the Tabular Data Stream Protocol, TDS is the low-level proprietary protocol used by SQL Server to handle client and server communication. This Namespace is working with SQL Server7.0 and higher

Difference between OnClick & OnCommand

Difference is additional information CommandName, CommandArgs Properties are passed with Command Argument

What is Web Services

Web Services can be accessed by any language, using any component model, running on any operating system

Calling a .NET Component from COM

When a .NET component is called from COM, the runtime again generates a COM callable wrapper (CCW). The CCW acts as a proxy between the unmanaged COM code and the managed .NET code. The CCW is responsible for handling all interaction between the COM client and the managed object

Calling a COM Component from .NET

When a COM object is called from .NET, the runtime generates a runtime callable wrapper (RCW). The RCW acts as a proxy for the unmanaged object. (This wrapper turns the COM interfaces exposed by the COM component into .NET Framework-compatible interfaces.)
The RCW is responsible for handling all interaction between the .NET client code and the COM component

What is Managed code, UnManaged Code and Managed data?

Code that targets the runtime is known as managed code, while code that does not target the runtime is known as unmanaged code.

Closely related to managed code is managed data—data that is allocated and de-allocated by the common language runtime's garbage collector. C#, Visual Basic, and JScript .NET data is managed by default.

Reqular Expression in javascript

Decimal : \d{1,5}(\.\d{1,2})?
Integer :\d{2}
Money : /^\d+\.\d{2}$/;
Age = /^(1[0-2]\d\d{1,2})$/;

What Is WCF

Windows Communication Foundation (WCF) is an SDK for developing and deploying services on Windows. WCF provides a runtime environment for your services, enabling you to expose CLR types as services, and to consume other services as CLR types.

What are the seven layers of the OSI model?

The layers are
  • Physical
  • Data link
  • Network
  • Transport
  • Session
  • Presentation
  • Application layers.



What is VML ?

Vector Markup Language (VML) http://www.w3.org/TR/NOTE-VML

What is PCDATA

PCDATA means parsed character data. Think of character data as the text found between the start tag and the end tag of an XML element. PCDATA is text that will be parsed by a parser. Tags inside the text will be treated as markup and entities will be expanded.

Update Query using another table

     Update Emp1 
     Set Emp1.sal = Emp2.sal 
     From Employee Emp1, Employee2 Emp2
     Where Emp1.empid = Emp2.empid 

What is joins ?

SQL joins are used to query data from two or more tables, based on a relationship between certain columns in these tables
Types of Joins
  • Inner join  :
    A join that displays only the rows that have a match in both joined tables. (This is the default type of join in the Query Designer.)
     
  • Outer join :
    • Left outer join :
      All rows from the first-named table (the "left" table, which appears leftmost in the JOIN clause) are included. Unmatched rows in the right table do not appear. (*=)
       
    • Right outer join  :
      All rows in the second-named table (the "right" table, which appears rightmost in the JOIN clause) are included. Unmatched rows in the left table are not included. (=*)
       
    • Full outer join  :
      All rows in all joined tables are included, whether they are matched or not.
       
  • Cross join  :
    A join whose result set includes one row for each possible pairing of rows from the two tables.
Note Columns containing NULL do not match any values when you are creating an inner join and are therefore excluded from the result set. Null values do not match other null values.


How to find 6th highest salary

SELECT TOP 1 salary
FROM (SELECT DISTINCT TOP 6 salary
FROM employee
ORDER BY salary DESC) a
ORDER BY salary

How to delete the rows which are duplicate?

SET ROWCOUNT 1
DELETE yourtable
FROM yourtable a
WHERE (SELECT COUNT(*) FROM yourtable b WHERE b.name1 = a.name1 AND b.age1 = a.age1) > 1
WHILE @@rowcount > 0
  DELETE yourtable
  FROM yourtable a
  WHERE (SELECT COUNT(*) FROM yourtable b WHERE b.name1 = a.name1 AND b.age1 = a.age1) > 1
SET ROWCOUNT 0

What is Page Split

Page Split: When a new row is added to a full index page, SQL Server moves approximately half the rows to a new page to make room for the new row. This reorganization is known as a page split .

More: When you create a clustered index, the data in the table is stored in the data pages of the database according to the order of the values in the indexed columns. When new rows of data are inserted into the table or the values in the indexed columns are changed, SQL Server may have to reorganize the storage of the data in the table to make room for the new row and maintain the ordered storage of the data. This also applies to nonclustered indexes. When data is added or changed, SQL Server may have to reorganize the storage of the data in the nonclustered index pages. When a new row is added to a full index page, SQL Server moves approximately half the rows to a new page to make room for the new row. This reorganization is known as a page split. Page splitting can impair performance and fragment the storage of the data in a table.

Alternative way instead of SELECT COUNT(*) statement.

SELECT rows FROM sysindexes WHERE id = OBJECT_ID('RD_AlertsHistory') AND indid < 2

What is Fill Factor

An attribute of an index that defines the amount of free space on each page of the index.

FILLFACTOR accommodates future expansion of table data and reduces the potential for page splits. FILLFACTOR is a value from 1 through 100 that specifies the percentage of the index page to be left empty

What is denormalization and when would you go for it?

As the name indicates, denormalization is the reverse process of normalization. It’s the controlled introduction of redundancy in to the database design. It helps improve the query performance as the number of joins could be reduced.

View Advantage & Disadvantage

  • Data security - no need to give permission on the table, infact a view can be created, having only selected number of coloums in its definition. So user will only be able to see those coloums.
  • Simplicity - a very complicated query can be saved as a view defenition. when needed can be called by its view name.
  • Removes dependency - Can be very helpful to remove the dependecny from the underlying tables. Suppose a view is created by joining several tables. After some time, there are some changes on the tables, so only defenition of view can be changed and there is no need to change all the code where view is used.
  • No space - takes no space ( except materialized view )

What is View?

A view is a virtual table made up of data from base tables and other views, but not stored separately.

Normalization with example

  • Unnormalized Table:

        Student#   Advisor   Adv-Room  Class1   Class2   Class3
        -------------------------------------------------------
        1022       Jones      412      101-07   143-01   159-02
        4123       Smith      216      201-01   211-02   214-01
     
  • 1NF: Eliminate Repeating Groups
    Make a separate table for each set of related attributes, and give each table a primary key.
    Each field contains at most one value from its attribute domain. 

    Tables should have only two dimensions. Since one student has several classes, these classes should be listed in a separate table. Fields Class1, Class2, & Class3 in the above record are indications of design trouble.
           Student#   Advisor   Adv-Room    Class#
           ---------------------------------------
           1022      Jones      412       101-07
           1022      Jones      412       143-01
           1022      Jones      412       159-02
           4123      Smith      216       201-01
           4123      Smith      216       211-02
           4123      Smith      216       214-01
    
  • 2NF: Eliminate Redundant Data
    If an attribute depends on only part of a multi-valued key, remove it to a separate table.

    Note the multiple Class# values for each Student# value in the above table. Class# is not functionally dependent on Student# (primary key), so this relationship is not in second normal form.
        Students:   Student#    Advisor   Adv-Room
                    ------------------------------
                    1022        Jones       412
                    4123        Smith       216
    
        Registration:   Student#    Class#
                        ------------------
                        1022        101-07
                        1022        143-01
                        1022        159-02
                        4123        201-01
                        4123        211-02
                        4123        214-01
  • 3NF: Eliminate Columns Not Dependent On Key
    If attributes do not contribute to a description of the key, remove them to a separate table.
    All attributes must be directly dependent on the primary key.

    In the last example, Adv-Room (the advisor's office number) is functionally dependent on the Advisor attribute. The solution is to move that attribute from the Students table to the Faculty table, as shown below:
        Students:   Student#    Advisor
                    -------------------
                    1022        Jones
                    4123        Smith
    
        Faculty:    Name    Room    Dept
                    --------------------
                    Jones   412     42
                    Smith   216     42
  • 4NF / BCNF: Boyce-Codd Normal Form
    If there are non-trivial dependencies between candidate key attributes, separate them out into distinct tables.

What is Normalization

normalization is a technique for designing relational database tables to minimize redundancy.

What are different normalization forms?
  • 1NF: Eliminate Repeating Groups
  • 2NF: Eliminate Redundant Data
  • 3NF: Eliminate Columns Not Dependent On Key
  • 4NF / BCNF: Boyce-Codd Normal Form
  • 4NF: Isolate Independent Multiple Relationships
  • 5NF: Isolate Semantically Related Multiple Relationships
  • ONF: Optimal Normal Form
  • DKNF: Domain-Key Normal Form

Difference between char and nvarchar / char and varchar data-type?

char[(n)] - Fixed-length non-Unicode character data with length of n bytes. n must be a value from 1 through 8,000. Storage size is n bytes. The SQL-92 synonym for char is character.


nvarchar(n) - Variable-length Unicode character data of n characters. n must be a value from 1 through 4,000. Storage size, in bytes, is two times the number of characters entered. The data entered can be 0 characters in length. The SQL-92 synonyms for nvarchar are national char varying and national character varying.

varchar[(n)] - Variable-length non-Unicode character data with length of n bytes. n must be a value from 1 through 8,000. Storage size is the actual length in bytes of the data entered, not n bytes. The data entered can be 0 characters in length. The SQL-92 synonyms for varchar are char varying or character varying.

How insert in a table using xml file/data

XML insertion
CREATE PROC sp_insert_employee @empdata ntext 
AS 
       DECLARE @hDoc int 
    EXEC sp_xml_preparedocument @hDoc OUTPUT, @empdata 
    INSERT INTO Employee 
      SELECT * 
      FROM OPENXML(@hDoc, '/Employee') 
            WITH Employee 
     EXEC sp_xml_removedocument @hDoc 

XML Update
CREATE PROC sp_update_employee @empdata ntext     
AS     
DECLARE @hDoc int       
exec sp_xml_preparedocument @hDoc OUTPUT,@empdata  
UPDATE Employee     
SET     
      Employee.fname = XMLEmployee.fname,    
      Employee.lname = XMLEmployee.lname      
FROM OPENXML(@hDoc, '/root/Employee')   
             WITH Employee XMLEmployee    
WHERE  Employee.eid = XMLEmployee.eid    
EXEC sp_xml_removedocument @hDoc    
SELECT   *    
from      Employee 
FOR XML AUTO 

SELECT statement syntax

SELECT select_list
[INTO new_table_]
FROM table_source
[WHERE search_condition]
[GROUP BY group_by_expression]
[HAVING search_condition]
[ORDER BY order_expression [ASC | DESC] ]

How to improve performance of a poor performing query?

First have a look on the following things based on the query:
  • Check indexes
  • Check Table scans
  • Missing or out of date statistics
  • Blocking
  • Excess recompilations of stored procedures
  • Procedures and triggers without SET NOCOUNT ON
  • Poorly written query with unnecessarily complicated joins
  • Too much normalization
  • Excess usage of cursors and temporary tables.
Some of the tools/ways that help you troubleshooting performance problems are:
  • SET SHOWPLAN_ALL ON
  • SET SHOWPLAN_TEXT ON
  • SET STATISTICS IO ON
  • SQL Server Profile
  • Windows NT /2000 Performance monitor
  • Graphical execution plan in Query Analyzer
  • Index tuning Wizard

How can I enforce to use particular index?

You can use index hint (index=) after the table name.

SELECT au_lname FROM authors (index=aunmind)

Index Optimization tips

  • Every index increases the time in takes to perform INSERTS, UPDATES and DELETES, so the number of indexes should not be very much. Try to use maximum 4-5 indexes on one table, not more.
  • If you have read-only table, then the number of indexes may be increased.
  • Keep your indexes as narrow as possible. This reduces the size of the index and reduces the number of reads required to read the index.
  • Try to create indexes on columns that have integer values rather than character values.
  • If you create a composite (multi-column) index, the order of the columns in the key are very important. Try to order the columns in the key as to enhance selectivity, with the most selective columns to the leftmost of the key.
  • If you want to join several tables, try to create surrogate integer keys for this purpose and create indexes on their columns.
  • Create surrogate integer primary key (identity for example) if your table will not have many insert operations.
  • Clustered indexes are more preferable than nonclustered, if you need to select by a range of values or you need to sort results set with GROUP BY or ORDER BY.
  • If your application will be performing the same query over and over on the same table, consider creating a covering index on the table.
  • You can use the SQL Server Profiler Create Trace Wizard with "Identify Scans of Large Tables" trace to determine which tables in your database may need indexes. This trace will show which tables are being scanned by queries instead of using an index.
  • You can use sp_MSforeachtable undocumented stored procedure to rebuild all indexes in your database. Try to schedule it to execute during CPU idle time and slow production periods.
    sp_MSforeachtable @command1="print '?' DBCC DBREINDEX ('?')"

Disadvantages of cursors

  • Each time you fetch a row from the cursor, it results in a network roundtrip.
  • Cursors are also costly because they require more resources and temporary storage (results in more IO operations).
  • Further, there are restrictions on the SELECT statements that can be used with some types of cursors.

Advantages and Disadvantages of indexs

  • Advantage
    If you create an index on each column of a table, it improves the query performance, as the query optimizer can choose from all the existing indexes to come up with an efficient execution plan.
     
  • Disadvantage
    • At the same time, data modification operations (such as INSERT, UPDATE, DELETE) will become slow, as every time data changes in the table, all the indexes need to be updated.
    • Another disadvantage is that, indexes need disk space, the more indexes you have, more disk space is used.

Index - SQL

Indexes in SQL Server are similar to the indexes in books. They help SQL Server retrieve the data quicker.
Types of indexes
  • Clustered indexes :
    When you create a clustered index on a table, all the rows in the table are stored in the order of the clustered index key. So, there can be only one clustered index per table.
     
  • Non-clustered indexes :
    Non-clustered indexes have their own storage separate from the table data storage. Non-clustered indexes are stored as B-tree structures (so do clustered indexes), with the leaf level nodes having the index key and it’s row locater.

Cursors - SQL

When you write code for a transaction that retrieves a single row of results, you can use a SELECT INTO statement. This is called a singleton SELECT statement.

When you write code for a transaction where the result set includes several rows of data, you must declare and use a cursor. A cursor is a mechanism you can use to fetch rows one at a time.

The four API server cursor types supported by SQL Server are:
  • Static cursors
    Static cursors detect few or no changes but consume relatively few resources while scrolling, although they store the entire cursor in tempdb.
     
  • Dynamic cursors
    Dynamic cursors detect all changes but consume more resources while scrolling, although they make the lightest use of tempdb.
     
  • Keyset-driven cursors
    Keyset-driven cursors lie in between, detecting most changes but at less expense than dynamic cursors.
     
  • Forward-only cursors

Difference between Primary Key and Unique Key

By default primary key creates a clustered index on the column, where are unique creates a nonclustered index by default.

Another major difference is that, primary key doesn't allow NULLs, but unique key allows one NULL only.

Constraints

Constraints enable the RDBMS enforce the integrity of the database automatically, without needing you to create triggers, rule or defaults.
Different types of constraints.
  • NOT NULL specifies that the column does not accept NULL values.
  • UNIQUE constraints enforce the uniqueness of the values in a set of columns.
  • PRIMARY KEY constraints identify the column or set of columns whose values uniquely identify a row in a table.
  • CHECK constraints enforce domain integrity by limiting the values that can be placed in a column.
  • FOREIGN KEY constraints identify the relationships between tables.
Column and Table Constraints
  • A column constraint is specified as part of a column definition and applies only to that column (the constraints in the earlier samples are column constraints).
  • A table constraint is declared independently from a column definition and can apply to more than one column in a table.

Table constraints must be used when more than one column must be included in a constraint.

Comparison of AFTER and INSTEAD OF triggers.

Function AFTER trigger INSTEAD OF trigger
Applicability Tables Tables and views
Quantity per table or view Multiple per triggering action (UPDATE, DELETE, and INSERT) One per triggering action (UPDATE, DELETE, and INSERT)
Cascading references No restrictions apply Are not allowed on tables that are targets of cascaded referential integrity constraints.
Execution After:
  • Constraint processing
  • Declarative referential actions
  • inserted and deleted tables creation
  • The triggering action
Before:
  • Constraint processing

In place of:

  • The triggering action

After:

  • inserted and deleted tables creation
Order of execution First and last execution may be specified Not applicable
text, ntext, and image column references in inserted and deleted tables Not allowed Allowed

Difference between DELETE TABLE and TRUNCATE TABLE commands?

  • DELETE TABLE is a logged operation, so the deletion of each row gets logged in the transaction log, which makes it slow.
      
  • TRUNCATE TABLE won't log the deletion of each row, instead it logs the deallocation of the data pages of the table, which makes it faster.

How to invoke a trigger on demand?

Triggers can’t be invoked on demand.

Tirggers - SQL

Triggers : Triggers are special kind of stored procedures that get executed automatically when an INSERT, UPDATE or DELETE operation takes place on a table.

Trigger Types :
  • AFTER
    AFTER triggers are executed after the action of the INSERT, UPDATE, or DELETE statement is performed. Specifying AFTER is the same as specifying FOR, which is the only option available in earlier versions of SQL Server. AFTER triggers can be specified only on tables.
    After trigger does not fire until the row or rows have been inserted and constraints have been checked and passed. Basically, AFTER triggers fire very late in the process.
     
  • INSTEAD OF
    INSTEAD OF triggers are executed in place of the usual triggering action. INSTEAD OF triggers can also be defined on views with one or more base tables, where they can extend the types of updates a view can support.

SQL Optimization Tips

Transact-SQL Optimization Tips
  • Use views and stored procedures instead of heavy-duty queries.
    This can reduce network traffic, because your client will send to server only stored procedure or view name (perhaps with some parameters) instead of large heavy-duty queries text. This can be used to facilitate permission management also, because you can restrict user access to table columns they should not see.
     
  • Try to use constraints instead of triggers, whenever possible.
    Constraints are much more efficient than triggers and can boost performance. So, you should use constraints instead of triggers, whenever possible.
     
  • Use table variables instead of temporary tables.
    Table variables require less locking and logging resources than temporary tables, so table variables should be used whenever possible. The table variables are available in SQL Server 2000 only.
     
  • Try to use UNION ALL statement instead of UNION, whenever possible.
    The UNION ALL statement is much faster than UNION, because UNION ALL statement does not look for duplicate rows, and UNION statement does look for duplicate rows, whether or not they exist.
     
  • Try to avoid using the DISTINCT clause, whenever possible.
    Because using the DISTINCT clause will result in some performance degradation, you should use this clause only when it is necessary.
     
  • Try to avoid using SQL Server cursors, whenever possible.
    SQL Server cursors can result in some performance degradation in comparison with select statements. Try to use correlated sub-query or derived tables, if you need to perform row-by-row operations.
     
  • Try to avoid the HAVING clause, whenever possible.
    The HAVING clause is used to restrict the result set returned by the GROUP BY clause. When you use GROUP BY with the HAVING clause, the GROUP BY clause divides the rows into sets of grouped rows and aggregates their values, and then the HAVING clause eliminates undesired aggregated groups. In many cases, you can write your select statement so, that it will contain only WHERE and GROUP BY clauses without HAVING clause. This can improve the performance of your query.
     
  • If you need to return the total table's row count, you can use alternative way instead of SELECT COUNT(*) statement.
    Because SELECT COUNT(*) statement make a full table scan to return the total table's row count, it can take very many time for the large table. There is another way to determine the total row count in a table. You can use sysindexes system table, in this case. There is ROWS column in the sysindexes table. This column contains the total row count for each table in your database. So, you can use the following select statement instead of SELECT COUNT(*): SELECT rows FROM sysindexes WHERE id = OBJECT_ID('table_name') AND indid < 2 So, you can improve the speed of such queries in several times.
     
  • Include SET NOCOUNT ON statement into your stored procedures to stop the message indicating the number of rows affected by a T-SQL statement.
    This can reduce network traffic, because your client will not receive the message indicating the number of rows affected by a T-SQL statement.
     
  • Try to restrict the queries result set by using the WHERE clause.
    This can results in good performance benefits, because SQL Server will return to client only particular rows, not all rows from the table(s). This can reduce network traffic and boost the overall performance of the query.
     
  • Use the select statements with TOP keyword or the SET ROWCOUNT statement, if you need to return only the first n rows.
    This can improve performance of your queries, because the smaller result set will be returned. This can also reduce the traffic between the server and the clients.
     
  • Try to restrict the queries result set by returning only the particular columns from the table, not all table's columns.
    This can results in good performance benefits, because SQL Server will return to client only particular columns, not all table's columns. This can reduce network traffic and boost the overall performance of the query.
     

CLS & CTS

Common Language Specification (CLS) : Common Language Specification (CLS), which is a set of basic language features needed by many applications, has been defined. It's a subset of the common type system. Targeting the CLS is an excellent way to ensure cross-language interoperation.

Common Type System (CTS)  : The CLR is based on a type system and a programming model that are collectively known as the Common Type System (CTS). The common type system establishes a framework that enables cross-language integration, type safety, and high-performance code execution. Ex VB.NET Integer and a C# int are both represented in IL code as System.Int32

Finally keyword

One example is if you have an Exit Sub statement in your catch block. Normally this statement would exit the subroutine immediately, but in this situation the Finally Block is executed first.

Another example is in an ASP.NET app and you have a Response.Redirect statement in your Catch block, once again the Finally Block would be called before the redirect happens.

Another example is if there is another error that happens within your Catch block code, normally it would be immediately raised to the calling code, but in this situation the Finally Block is called first.


Delegates vs. Interfaces

Delegates are useful when:
  • A single method is being called.
  • A class may want to have multiple implementations of the method specification.
  • It is desirable to allow using a static method to implement the specification.
  • An event-like design pattern is desired (for more information, see the Events Tutorial).
  • The caller has no need to know or obtain the object that the method is defined on.
  • The provider of the implementation wants to "hand out" the implementation of the specification to only a few select components.
  • Easy composition is desired.
Interfaces are useful when:
  • The specification defines a set of related methods that will be called.
  • A class typically implements the specification only once.
  • The caller of the interface wants to cast to or from the interface type to obtain other interfaces or classes.

Assembly

Assembly Manifest : The metadatfor the assembly. It contains all of the information needed to describe the assembly to the common language runtime.

Private assembly : An assembly that is used by only one application. In .NET Framework programming, most assemblies are private assemblies.

Satellite assembly : When localizing an application, assemblies that contain alternate sets of resources to be used in the application for different cultures.

Strong Name : Name that uniquely identifies an assembly. It consists of the assembly’s name, version, and culture information as well as public key encrypted by private key. An assembly must have strong name to be installed to the Global Assembly Cache (GAC).

Static Assemblies : Static assemblies can include .NET Framework types (interfaces and classes), as well as resources for the assembly (bitmaps, JPEG files, resource files, and so on). Static assemblies are stored on disk in portable executable (PE) files.

Dynamic Assemblies: You can also use the .NET Framework to create dynamic assemblies, which are run directly from memory and are not saved to disk before execution. You can save dynamic assemblies to disk after they have executed.

Expanding All Subfolders in Explorer

To quickly have Explorer expand all subfolders for a selected drive or folder, simply press the asterisk (*) key on the numeric keypad.

Repositioning a wallpaper

Normally, you only options for displaying a background bitmap are tiled, centered, or stretch to fit (with the Plus Pack).
You can edit the registry and have a third option which is to place the bitmap anywhere on your screen by specifying the X and Y coordinates.
  1. Start Regedit
  2. Go to HKEY_CURRENT_USER / Control Panel / Desktop
  3. Create new Strings called WallpaperOriginX and WallpaperOriginY
  4. Give them values to position them around your desktop
  5. The bitmap must be smaller than your desktop size

Opening a Command Prompt to a Particular Directory from Explorer

If you want to open a command prompt to a directory that is selected in the Explorer:
  • Start Regedit  
  • Go to HKEY_CLASSES_ROOT \ Directory \ shell  
  • Create a new key called Command  
  • Give it the value of the name you want to appear in the Explorer. Something like Open DOS Box  
  • Under this create a new key called command  
  • Give it a value of " cmd.exe cd %1 " (no quotes)  
  • Now when you are in the Explorer, right click on a folder, select Open DOS Box, and a command prompt will open to the selected directory.

Open Help file in windows

hh.exe mk:@MSITStore:C:\WINNT\Help\windows.chm::/ntcmds.htm

Crystal Report basics

Top sections of CR    

  • Report Header
  • Page Header
  • Details
  • Report Footer
  • Page Footer
  • Additional Report Sections
  • Group Header
  • Group Footer  

Report Header 
Objects placed in the Report Header section print once, at the beginning of the report.

The Report Header section generally contains the report title and other information you want to appear only at the beginning of the report.
  • Charts and cross-tabs placed in this section contain data for the entire report.
  • Formulas placed in this section are evaluated once, at the beginning of the report.
Page Header
Objects placed in the Page Header section print at the beginning of each new page. The Page Header section generally contains information that you want to appear at the top of each page. This can include text fields such as chapter names, document name, or other similar information. This section can also be used to contain field titles, which will then display as labels above the columns of field data in the report.
  • Charts or cross-tabs cannot be placed in this section.
  • Formulas placed in this section are evaluated once per page, at the beginning of each new page.

Details
Objects placed in the Details section print with each new record. The Details section contains data for the body of the report. The bulk of the report data usually appears in this section. When the report is run, the Details section is re-printed for each record. For example, if you add a database object to the Details section, and this database object contains 100 records, then the report will print 100 individual detail sections at runtime.

  • Charts or cross-tabs cannot be placed in this section.
  • Formulas placed in this section are evaluated once for each record.   
Report Footer 
Objects placed in the Report Footer section print once at the end of the report. This section is used to contain information you want to appear only once at the end of the report, such as grand totals.

  • Charts and cross-tabs placed in this section contain data for the entire report.
  • Formulas placed in this section are evaluated once, at the end of the report. 
  • Page Footer   
    Objects placed in the Page Footer section print at the bottom of each page.

    This section usually contains the page number and any other information you want to appear at the bottom of each page.
       
    • Charts and cross-tabs cannot be placed in this section.
    • Formulas placed in this section are evaluated once per page, at the end of each new page.

    Additional Report Sections    
    If a group, summary, or subtotal is added to the report, the program creates two additional sections: the Group Header and the Group Footer.  
     
    Group Header  
    Objects placed in the Group Header section print at the beginning of each new group.

    This section typically holds the group name field, and it can also be used to display charts or cross-tabs that include data specific to the group. The Group Header section is printed once at the beginning of each group.
    • Charts and cross-tabs placed in this section contain data just for the group.
    • Formulas placed in this section are evaluated once for each group, at the beginning of the group.    

    Group Footer  
    Objects placed in the Group Footer section print at the end of each group. This section generally holds the summary value, if any, and can be used to display charts or cross-tabs. The Group Footer section is printed once at the end of each group.
    • Charts and cross-tabs placed in this section contain data just for the group.
    • Formulas placed in this section are evaluated once for each group, at the end of the group.   

    Report Experts
    • Standard
    • Form Letter
    • Form
    • Cross-Tab
    • Subreport
    • Mail Label
    • Drill Down

    Report Processing Model
    Crystal Reports uses a three-pass reporting method to generate reports. A pass is a process that Crystal Reports uses each time the data is read and manipulated.

    What is DiffGram

    A DiffGram is an XML format that is used to identify current and original versions of data elements. The DataSet uses the DiffGram format to load and persist its contents, and to serialize its contents for transport across a network connection.

    When a DataSet is written as a DiffGram, it populates the DiffGram with all the necessary information to accurately recreate the contents, though not the schema, of the DataSet, including column values from both the Original and Current row versions, row error information, and row order.

    adapter.Fill(ds, "DtSet")

    ' Write XML in DiffGram format
    ds.WriteXml("DiffGramFile.xml", XmlWriteMode.DiffGram)


    Whats an assembly

    Assemblies are the building blocks of .NET Framework applications;
    They form the fundamental unit of deployment, version control, reuse, activation scoping, and security permissions.
    An assembly is a collection of types and resources that are built to work together and form a logical unit of functionality.

    Difference between inline and code behind

    ASP.NET supports two modes of page development: Page logic code that is written inside <script runat="server"> blocks within an .aspx file and dynamically compiled the first time the page is requested on the server.

    Page logic code that is written within an external class that is compiled prior to deployment on a server and linked "behind" the .aspx file at run time.

    ADO and ADO.NET differences

    ADO.NET ADO
    Disconnected Architecture. Connected Architecture
    choice of either using client-side or server-side cursors Create client-side cursors only
    ADO.NET allows you to manipulate your data using XML as the primary means ADO allows you to persist records in XML format
    ADO.NET's are stateless(internet) ADO's are stateful(TCP/IP)
    Table Locking is not Possible Locking is Possible

    How do you generate a proxy class for webservice

    1.Use the Wsdl.exe tool to generate the source code file for the proxy class.
         wsdl.exe /l:cs http://www.yoursite.com/Services/WeatherService.asmx?wsdl
         wsdl.exe /l:vb http://www.yoursite.com/Services/WeatherService.asmx?wsdl

    2.Compile the source code file for the proxy class.
         vbc /t:library /r:System.dll,System.Web.Services.dll, System.Xml.dll WeatherService.vb
         csc /t:library /r:System.dll,System.Web.Services.dll, System.Xml.dll WeatherService.vb

    3.Copy the compiled proxy class into the ASP.NET application's /bin directory.
           The above statement references all the needed assemblies to compile the WeatherService.vb file to a DLL file. After the class is compiled, you need to copy it to your ASP.NET application's /bin directory so that it is visible to your ASP.NET pages.

    What is Disco?

    The Web Services Discovery tool discovers the URLs of XML Web services located on a Web server and saves documents related to each XML Web service on a local disk.

    What is the Web service protocol stack?

    The Web service protocol stack is an evolving set of protocols used to define, discover, and implement Web services. The core protocol stack consists of four layers:

    Service Transport: This layer is responsible for transporting messages between applications. Currently, this includes HTTP, SMTP, FTP, and newer protocols, such as Blocks Extensible Exchange Protocol (BEEP).

    XML Messaging: This layer is responsible for encoding messages in a common XML format so that messages can be understood at either end. Currently, this includes XML-RPC and SOAP.

    Service Description: This layer is responsible for describing the public interface to a specific Web service. Currently, service description is handled via the WSDL.

    Service Discovery: This layer is responsible for centralizing services into a common registry, and providing easy publish/find functionality. Currently, service discovery is handled via the UDDI.

    WebMethod Attribute in Asp.Net Web Service.

    The WebMethod attribute has six associated properties to document and change the behavior of your web method. They are:


    • Description
    • MessageName
    • EnableSession
    • CacheDuration
    • TransactionOption
    • BufferResponse

     The first two properties are used to document a web method, while the others affect its behavior.

    What is SOAP?

    SOAP is an XML-based protocol for exchanging information between applications. Although SOAP can be used in a variety of messaging systems and can be delivered via a variety of transport protocols, the main focus of SOAP is Remote Procedure Calls (RPC) transported via HTTP.

    The Simple Object Access Protocol (SOAP) is a platform-independent protocol that uses XML to make remote procedure calls.

    What namespaces are imported by default in ASMX files?

    The following namespaces are imported by default. Other namespaces must be imported manually.
    • System,
    • System.Collections,
    • System.ComponentModel,
    • System.Data,
    • System.Diagnostics,
    • System.Web,System.Web.Services

    Is it possible to prevent a browser from caching an ASPX page?

    Just call SetNoStore on the HttpCachePolicy
    <%     Response.Cache.SetNoStore ();
        Response.Write (DateTime.Now.ToLongTimeString ()); %>

    What are VSDISCO files?

    VSDISCO files are DISCO files that support dynamic discovery of Web services. If you place the following VSDISCO file in a directory on your Web server, for example, it returns references to all ASMX and DISCO files in the host directory and any subdirectories not noted in <EXCLUDE>elements:
    <DYNAMICDISCOVERY xmlns=”urn:schemas-dynamicdiscovery:disco.2000-03-17″>
    <EXCLUDE path=”_vti_cnf” />
    <EXCLUDE path=”_vti_pvt” />
    <EXCLUDE path=”_vti_log” />
    <EXCLUDE path=”_vti_script” />
    <EXCLUDE path=”_vti_txt” />
    </DYNAMICDISCOVERY>

    What is a formatter?

    A formatter is an object that is responsible for encoding and serializing data into messages on one end, and deserializing and decoding messages into data on the other end.

    What is DOM?

    Document Object Model (DOM) is a W3C specification that defines a standard (abstract) programming API to build, navigate and update XML documents.

    What is WSDL?

    WSDL (Web Services Description Language) is an XML-based language for describing Web services and how to access them.

    Files with the WSDL extension contain web service interfaces expressed in the Web Service Description Language (WSDL). WSDL is a standard XML document

    WSDL files are used to communicate interface information between web service producers and consumers. A WSDL description allows a client to utilize a web service’s capabilities without knowledge of the implementation details of the web service.


    What is UDDI?

    1. UDDI stands for Universal Description, Discovery and Integration
    2. UDDI is a directory for storing information about web services
    3. UDDI is a directory of web service interfaces described by WSDL
    4. UDDI communicates via SOAP
    5. UDDI is built into the Microsoft .NET platform

    Common Language Runtime (CLR)

    The common language runtime is the execution engine for .NET Framework applications. It provides a number of services 
    • Code management (loading and execution)
    • Memory Management
    • Thread Management
    • Garbage Collection
    • Conversion of IL to native code
    • Enforcement of code access security
    • Exception handling, including cross-language exceptions

    Generics

    Generics are the most powerful feature of C# 2.0. Generics allow you to define type-safe data structures, without committing to actual data types. Instead of writing a function or a class for a particular type, it can be written generally to use any type. When an instance of the generic class is instantiated, the type is specified.

    Eg. You might create a generic sorting class and when you create an instance of this, the type of entity it sorts is specified. One instance might sort ints, another doubles, and another payroll records.

    What Generics Cannot Do


    You cannot define generic Web services. That is, Web methods that use generic type parameters. The reason is that none of the Web service standards support generic services.

    You also cannot use generic types on a serviced component. The reason is that generics do not meet COM visibility requirements, which are required for serviced components (just like you could not use C++ templates in COM or COM+).




    What debugging tools come with the .NET SDK?

    1. CorDBG – command-line debugger. To use CorDbg, you must compile the original C# file using the /debug switch.
       
    2. DbgCLR – graphic debugger. Visual Studio .NET uses the DbgCLR.

    String and StringBuilder

    The data value may not be changed.

    Note: The variable value may be changed, but the original immutable data value was discarded and a new data value was created in memory.

    System.String - Immutable
    System.Text.StringBuilder - mutable

    What is the use of Partial keyword

    • A Partial class is a class that can be split into two or more classes. This means that a class can be physically separated into other parts of the class within the same namespace
    • In this code-behind model, the page is declared as a partial class, which enables both the page and code files to be compiled into a single class at runtime. The page code refers to the code-behind file in the CompilesWith attribute of the <%@ Page %> directive, specifying the class name in the ClassName attribute.

    Access Modifiers

    Accessibility

    Meaning

    public Access is not restricted.
    protected Access is limited to the containing class or types derived from the containing class.
    internal Access is limited to the current assembly.
    protected internal Access is limited to the current assembly or types derived from the containing class.
    private Access is limited to the containing type.
     
     

    Default

    Modifiers Allowed declared accessibility of the member
    enum public   None
    class private new, abstract, sealed, public, protected, internal, private, protected internal public, protected, internal, private, protected internal
    interface public new, Public, Friend, Protected, or Private. None
    struct private   public, internal, private

    delegate

     

    new, Public, Friend, Protected, or Private.

     

    Forms authentication

    A system by which unauthenticated requests are redirected to an HTML form using HTTP client-side redirection. The following example grants access to Kim and members of the Admins role, while denying it to John and all anonymous users:
    <configuration>
                <system.web>
                          <authentication mode="Forms">
                                    <forms name=".ASPXUSERDEMO" loginUrl="login.aspx" protection="All" timeout="60" />
                           </authentication>
                           <authorization>
                                
    <allow users="Ravi"/>
                                 <allow roles="Admins"/>
                                 <allow verb="POST" users="Kumar"/>
                                 <deny users="Preethi"/>
                                  <deny users="?"/>
                           </authorization>
                 </system.web>

         <location path="secureservice.asmx">
               <system.web>
                   <authorization>
                            <allow users="Administrator"/>
                            <allow users="DOMAIN\Bradley"/>
                   </authorization>
             </system.web>
        </location>
    </configuration>
    * - Refers to all identities
    ? - Refers to the anonymous identity
    After validating the credentials

    if ((UserEmail.Value == "someone@www.contoso.com") && (UserPass.Value == "password"))
               {
                     FormsAuthentication.RedirectFromLoginPage(UserEmail.Value, PersistCookie.Checked);
              }

    FormsAuthentication.SignOut method. This removes the authentication cookie regardless of whether it is temporary or permanent.

    Difference between new and override

    • Override is used to implement a inherited method that is marked as virtual or abstract in the base class.
       
    • New is used when the base class has not marked it's method as virtual or abstract, and requires an instance of the derived class to be called

    User Controls & Custom Controls

    Web user controls Web custom controls
    Easier to create Harder to create
    Limited support for consumers who use a visual design tool Full visual design tool support for consumers
    A separate copy of the control is required in each application Only a single copy of the control is required, in the global assembly cache
    Cannot be added to the Toolbox in Visual Studio Can be added to the Toolbox in Visual Studio
    Good for static layout Good for dynamic layout
    Web user controls are compiled dynamically at run time they cannot be added to the Toolbox, Web custom controls are compiled code,

    State Management

    ASP.NET supports various client-side and server-side options for state management.

     Client-Side  Server-Side
     ViewState             Application state       
     Hidden fields  Session state
     Cookies  Database
     Query strings  Cache
     Control State Profile Properties
     HttpContext.Current.Item            

    Authentication, Authorization, Impersonation & Delegation

    Authentication :
    This is the process of accepting credentials from a user and validating those credentials against a designated authority.
    ASP.NET authentication Types:
    1. Forms authentication
    2. Windows authentication
    3. Passport authentication
    4. Default authentication
    Authorization :
    This is the process of determining whether the proven identity is allowed to access a specific resource.
    ASP.NET authorization types:
    1. FileAuthorization
    2. UrlAuthorization
    1. * - Refers to all identities
    2. ? - Refers to the anonymous identity
    3. <authorization>
          <allow roles="Admins"/>
          <allow verb="GET" users="*"/>
          <allow verb="POST" users="Kim"/>
          <deny verb="POST" users="*"/> 
          <deny users="John"/>
          <deny users="?"/>
      </authorization>
      
    more info http://support.microsoft.com/kb/306590

    Impersonation :
    A This mechanism allows a server process to run using the security credentials of the client. When the server is impersonating the client, any operations performed by the server are performed using the client's credentials. Impersonation does not allow the server to access remote resources on behalf of the client.

    Delegation :
    A Like impersonation, delegation allows a server process to run using the security credentials of the client. However, delegation is more powerful and allows the server process to make calls to other computers while acting as the client.

    Maximum limit for File Upload ASP.NET.

    By default, ASP.NET permits only files that are 4,096 kilobytes (KB) (or 4 megabytes [MB]) or less to be uploaded to the Web server. To upload larger files, you must change the maxRequestLength parameter of the section in the Web.config file.

    Note When the maxRequestLength attribute is set in the Machine.config file and then a request is posted (for example, a file upload) that exceeds the value of maxRequestLength, a custom error page cannot be displayed. Instead, Microsoft Internet Explorer will display a "Cannot find server or DNS" error message.

    Advantage Of ASP.NET over ASP

    • Compiled Pages
       
    • Multiple language support
        
    • Caching Features: - Pages and even Parts of pages frequently requested can now be cached for better performances.
       
    • Server Controls - Server side components automate many common development tasks. These controls can detect the version of the browser and generate the proper HTML and JavaScript code.
        
    • Separation of Logic

     

    Asynchronous method

    A method call that returns to the caller immediately regardless of whether processing has completed. The results of processing are returned through another call on another thread. Asynchronous methods free the caller from having to wait until processing has finished.

    Difference between method overriding and overloading

    Overriding is the concept of having functions of same name and signature in different classes. one in the super class can be made virtual and other can override the functionality of virtual one and it is runtime polymorphism.

    Overloading is the concept of having functions of same name, but different signature in same class. They are differentiated by the compiler by their signatures and it is is designtime polymorphism

    What are the different forms of polymorphism?

    • Design/Compile time polymorphism
      • Function overloading
      • Operator overloading
         
    • Run time polymorphism
      • Function overriding

    Write a program to print the next or before even or odd numbers.

    x = x + (-1)x

    Write a program to interchange 2 variables without using the third one.

    • a = (a + b) - (b = a)
       
    • a = a + b ;
      b = a - b ;
      a = a - b ;

    What’s the difference between an interface and abstract class?


    Feature

    Interface

    Abstract class

    Multiple inheritance

    A class may inherit several interfaces.

    A class may inherit only one abstract class.

    Default implementation

    All methods are abstract  there is no implementation

    An abstract class can provide complete, default code and/or just the
    details that have to be overridden.

    Constants

    Only Static final constants.

    Both instance and static constants are possible.

    Core VS Peripheral

    Interfaces are used to define the peripheral abilities of a class. In
    other words both Human and Vehicle can inherit from a IMovable
    interface.

    An abstract class defines the core identity of a class and there it is
    used for objects of the same type.

    Homogeneity

    If the various implementations only share method signatures then it is
    better to use Interface.

    If the various implementations are of the same kind and use common
    behaviour or status then abstract class is better to use.

    Speed

    Requires more time to find the actual method in the corresponding
    classes.

    Fast

    Adding functionality

    If we add a new method to an Interface then we have to track down all
    the implementations of the interface and define implementation for the
    new method.

    If we add a new method to an abstract class then we have the option of
    providing default implementation and therefore all the existing code
    might work properly.

    Modifiers 

    No accessibility modifiers are allowed.

    May have accessibility modifiers.

    What happens if you inherit multiple interfaces and they have conflicting method names?

    It’s up to you to implement the method inside your own class, so implementation is left entirely up to you. This might cause a problem on a higher-level scale if similarly named methods from different interfaces expect different data, but as far as compiler cares you’re okay.

    Why can’t you specify the accessibility modifier for methods inside the interface?

    They all must be public, and are therefore public by default.

    When do you absolutely have to declare a class as abstract?

    • When the class itself is inherited from an abstract class, but not all base abstract methods have been overridden.
       
    • When at least one of the methods in the class is abstract.

    When to use interface

    • Interfaces are better suited to situations in which your applications require many possibly unrelated object types to provide certain functionality.
        
    • Interfaces are more flexible than base classes because you can define a single implementation that can implement multiple interfaces.
        
    • Interfaces are better in situations in which you do not need to inherit implementation from a base class.
        
    • Interfaces are useful in cases where you cannot use class inheritance. For example, structures cannot inherit from classes, but they can implement interfaces.
       

    Object Oriented Design Principle

    • Identify interacting objects.
       
    • Characterize each object, establish attributes.
       
    • Identify the data and operations within each object.
       
    • Identify requests answered by each object
        
    • Identity services required of other objects
        
    • Establish relationships to other objects
        
    • Group similar objects together
        
    • Implement common super classes 
       
    • Implement different objects as classes

    Structures

    Not everything in the real world should be represented as a class. Structures are suitable to represent lightweight objects. Structures can have methods and properties and are useful for defining types that act as user-defined primitives, but contain arbitrary composite fields. The .NET Framework defines some structures such as System.Drawing.Rectangle, System.Drawing.Point, and System.Drawing.Color.

    Abstract class

    An abstract class is a parent class that allows inheritance but can never be instantiated. Abstract classes contain one or more abstract methods that do not have implementation.

    What are enumerators?

    enum's are data type & integer repesentation array in understandable form like-

    enum {monday, tuesday, ... sunday };

    Characteristics of OOPs

    • Object
      Object is the basic unit of object-oriented programming. Objects are identified by its unique name. An object represents a particular instance of a class. There can be more than one instance of an object. Each instance of an object can hold its own relevant data.
    • Classes
      Objects with similar properties and methods are grouped together to form a Class. Thus a Class represent a set of individual objects. Characteristics of an object are represented in a class as Properties. The actions that can be performed by objects becomes functions of the class and is referred to as Methods.

    • Encapsulation and Data hiding
      Data Encapsulation combines data and functions into a single unit called Class. When using Data Encapsulation, data is not accessed directly; it is only accessible through the functions present inside the class. Data Encapsulation enables the important concept of data hiding possible.

    • Inheritance
      Inheritance is the process of forming a new class from an existing class or base class.
      Or
      One Object can contains the properties of one or more objects.

    • Polymorphism.
      Polymorphism allows objects to be represented in multiple forms. Even though classes are derived or inherited from the same parent class, each derived class will have its own behavior. Polymorphism is a concept linked to inheritance and assures that derived classes have the same functions even though each derived class performs different operations.

    .NET Framework 4 File IO Features

    New methods are added to the System.IO.File class in .NET framework 4.0 for reading and writing text files.
    ReadLines
    In earlier version we have used File.ReadAllLines method which returns a string array of all lines in the file.
    String[] lines = File.ReadAllLines("file.txt");
    The issue is it must read all lines and allocate an array to return. For small files its ok but large files it is problematic because it block until all the lines are loaded into the memory.
    The new method ReadLines in .NET framework 4 returns IEnumerable<string> instead of string[]. The new method is much more efficient because it does not load all of the lines into memory at once;
    IEnumerable<string> lines = File.ReadLines("Largefile.txt");
    Foreach(var line in lines)
    The iteration actually driving the reading of the file.
    The other two new methods are File.WriteAllLines that takes an IEnumerable<string>
    Parameter and File.ApendAllLines that takes an IEnumerable<string> for appending lines to a file.
    EnumerateFiles
    In earlier version we have used GetFiles() method on directoryinfo object to get all files in the directory.
    DirectoryInfo directory = new DirectoryInfo(@"LargeDirectory");
    FileInfo[] files = directory.GetFiles();
    The issue is it must retrieve the complete list of files in the directory and then allocate an array to return. Here we have to wait all files to be retrieved.
    The second issue is whenever we call the properties on retrieved file it takes an additional call to the file which hinders the performance.
    In .NET 4, new method has added to Directory and DirectoryInfo that returns IEnumerable<T> instead of arrays to address the above issues.
    DirectoryInfo directory = new DirectoryInfo(@"LargeDirectory");
    IEnumerable<FileInfo> files = directory.EnumerateFiles();
    Unlike GetFiles, EnumerateFiles does not have to block until all of the files are retrieved. Now the DirectoryInfo object containing the file system during enumeration which include data about each file such as length and creation time.