Sunday 29 December 2013

Life Secure Question 2


7. What is generic list?

Generics provide the solution to a limitation in earlier versions of the common language runtime and the C# language in which generalization is accomplished by casting types to and from the universal base type Object. By creating a generic class, you can create a collection that is type-safe at compile-time

8. In which event we change our master page at runtime?

In our BasePage override OnPreInit method and assign the master page's master page as shown below
this.Page.Master.MasterPageFile = "~/SuperSitem.master";


9. What is Page Postback property?

You will have to know the difference between postback for the first time when the new page is loaded and postback for the second time. So postback is just posting back to the same page. Remember one thing, the postback contains all the information collected on the Initial page for processing.
Namespace:  System.Web.UI
Assembly:  System.Web (in System.Web.dll)

private void Page_Load()
{
    if (!IsPostBack)
    {
        // Validate initially to force asterisks
        // to appear before the first roundtrip.
        Validate();
    }
}


10. What is application domain?

An application domain is a mechanism (similar to a process in an operating system) used within the Common Language Infrastructure (CLI) to isolate executed software applications from one another so that they do not affect each other. Each application domain has its own virtual address space which scopes the resources for the application domain using that address space.
static void Main()
{
    // Create an Application Domain:
    System.AppDomain newDomain = System.AppDomain.CreateDomain("NewApplicationDomain");
 
    // Load and execute an assembly:
    newDomain.ExecuteAssembly(@"c:\HelloWorld.exe");
 
    // Unload the application domain:
    System.AppDomain.Unload(newDomain);
}



11.  What is difference between virtual and abstract method?

Abstract method: When a class contains an abstract method, that class must be declared as abstract. The abstract method has no implementation and thus, classes that derive from that abstract class, must provide an implementation for this abstract method.
Virtual method: A class can have a virtual method. The virtual method has an implementation. When you inherit from a class that has a virtual method, you can override the virtual method and provide additional logic, or replace the logic with your own implementation.


12. What is a Subquery, may it return more than one value?
Subquery or Inner query or Nested query is a query in a query. A subquery is usually added in the WHERE Clause of the sql statement.
Usually, a subquery should return only one record, but sometimes it can also return multiple records when used with operators like IN, NOT IN in the where clause. The query would be like,
SELECT first_name, last_name, subject 
FROM student_details 
WHERE games NOT IN ('Cricket', 'Football'); 


13. How we prevent our system to stop garbage collection?

GCLatencyMode oldMode = GCSettings.LatencyMode;
 
// Make sure we can always go to the catch block, 
// so we can set the latency mode back to `oldMode`
RuntimeHelpers.PrepareConstrainedRegions();
 
try
{
    GCSettings.LatencyMode = GCLatencyMode.LowLatency;
 
    // Generation 2 garbage collection is now
    // deferred, except in extremely low-memory situations
}
finally
{
    // ALWAYS set the latency mode back
    GCSettings.LatencyMode = oldMode;
}
 
That will allow you to disable the GC as much as you can. It won't do any large collections of objects until:
·         You call GC.Collect()
·         You set GCSettings.LatencyMode to something other than LowLatency
·         The OS sends a low-memory signal to the CLR
Please be careful when doing this, because memory usage can climb extremely fast while you're in thattry block. If the GC is collecting, it's doing it for a reason, and you should only seriously consider this if you have a large amount of memory on your system.








1. What is static method?

Static methods have no instances. They are called with the type name, not an instance identifier. They are slightly faster than instance methods because of this. Static methods can be public or private.
Static methods cannot access non-static class level members and do not have a 'this' pointer. Instance methods can access those members, but must be called through an instantiated object. This adds another level of indirection.
class Program
{
    static void MethodA()
    {
             Console.WriteLine("Static method");
    }
 
    void MethodB()
    {
             Console.WriteLine("Instance method");
    }
    static char MethodC()
    {
             Console.WriteLine("Static method");
             return 'C';
    }
    char MethodD()
    {
             Console.WriteLine("Instance method");
             return 'D';
    }
 
    static void Main()
    {
             //
             // Call the two static methods on the Program type.
             //
             Program.MethodA();
             Console.WriteLine(Program.MethodC());
             //
             // Create a new Program instance and call the two instance methods.
             //
             Program programInstance = new Program();
             programInstance.MethodB();
             Console.WriteLine(programInstance.MethodD());
    }
}


2. What is friend function?

There is no friend function in c# but you can use the `internal` access modifier which will make this class accessible to the 
other classes in the same assembly, but not accessible outside the assembly
. 

3. What is public access modifier?

The public keyword is an access modifier for types and type members. Public access is the most permissive access level. There are no restrictions on accessing public members, as in this example.
class SampleClass
{
    public int x; // No access restrictions.}


4. What is trigger in SQL server?

Triggers are special type of stored procedure that automatically execute when a DDL or DML statement associated with the trigger is executed. DML Triggers are used to evaluate data after data manipulation using DML statements. We have two types of DML triggers.

2. After Trigger (using FOR/AFTER CLAUSE)

This trigger fires after SQL Server completes the execution of the action successfully that fired it.
Example :If you insert record/row in a table then the trigger associated with the insert event on this table will fire only after the row passes all the checks, such as primary key, rules, and constraints. If the record/row insertion fails, SQL Server will not fire the After Trigger.

1. Instead of Trigger (using INSTEAD OF CLAUSE)

This trigger fires before SQL Server starts the execution of the action that fired it. This is much more different from the AFTER trigger, which fires after the action that caused it to fire. We can have an INSTEAD OF insert/update/delete trigger on a table that successfully executed but does not include the actual insert/update/delete to the table.
Example :If you insert record/row in a table then the trigger associated with the insert event on this table will fire before the row passes all the checks, such as primary key, rules, and constraints. If the record/row insertion fails, SQL Server will fire the Instead of Trigger.

5. What is Cursor in SQL server?

Cursor is a database objects to retrieve data from a result set one row at a time, instead of the T-SQL commands that operate on all the rows in the result set at one time. We use cursor when we need to update records in a database table in singleton fashion means row by row.

Life Cycle of Cursor

1.                 Declare Cursor

A cursor is declared by defining the SQL statement that returns a result set.

2.                 Open

A Cursor is opened and populated by executing the SQL statement defined by the cursor.

3.                 Fetch

When cursor is opened, rows can be fetched from the cursor one by one or in a block to do data manipulation.

4.                 Close

After data manipulation, we should close the cursor explicitly.

5.                 Deallocate

Finally, we need to delete the cursor definition and released all the system resources associated with the cursor.

Syntax to Declare Cursor

Declare Cursor SQL Comand is used to define the cursor with many options that impact the scalablity and loading behaviour of the cursor. The basic syntax is given below
1.       DECLARE cursor_name CURSOR
2.       [LOCAL | GLOBAL] --define cursor scope
3.       [FORWARD_ONLY | SCROLL] --define cursor movements (forward/backward)
4.       [STATIC | KEYSET | DYNAMIC | FAST_FORWARD] --basic type of cursor
5.       [READ_ONLY | SCROLL_LOCKS | OPTIMISTIC] --define locks
6.       FOR select_statement --define SQL Select statement
7.       FOR UPDATE [col1,col2,...coln] --define columns that need to be updated 

Syntax to Open Cursor

A Cursor can be opened locally or globally. By default it is opened locally. The basic syntax to open cursor is given below:
1.       OPEN [GLOBAL] cursor_name --by default it is local 

Syntax to Fetch Cursor

Fetch statement provides the many options to retrieve the rows from the cursor. NEXT is the default option. The basic syntax to fetch cursor is given below:
1.       FETCH [NEXT|PRIOR|FIRST|LAST|ABSOLUTE n|RELATIVE n]
2.      FROM [GLOBAL] cursor_name 
3.      INTO @Variable_name[1,2,..n] 

Syntax to Close Cursor

Close statement closed the cursor explicitly. The basic syntax to close cursor is given below:
1.       CLOSE cursor_name --after closing it can be reopen 

Syntax to Deallocate Cursor

Deallocate statement delete the cursor definition and free all the system resources associated with the cursor. The basic syntax to close cursor is given below:
1.       DEALLOCATE cursor_name --after deallocation it can't be reopen 

6. What is property in C#?

Properties get and set values. The C# language provides them as a convenient way to simplify syntax. They are implemented as methods in the intermediate language. They are standard access points to a class from external code.
Get:The get { } implementation must include a return statement. It can access any member on the class.
Set:The set { } implementation receives the implicit argument 'value', which is the value to which the property is assigned.
using System;
class Example
{
    int _number;
    public int Number
    {
             get
             {
                 return this._number;
             }
             set
             {
                 this._number = value;
             }
    }
}
 
class Program
{
    static void Main()
    {
             Example example = new Example();
             example.Number = 5; // set { }
             Console.WriteLine(example.Number); // get { }
    }
}

7. What is random function in C#?

Random number generators cannot return truly random numbers. They return instead sufficiently random numbers. With the Random type in the .NET Framework, we generate in our C# programs numbers that appear very random.

































1. What is Candidate key and alternate key in SQL server?

Super Key

Super key is a set of one or more than one keys that can be used to identify a record uniquely in a table.Example :Primary key, Unique key, Alternate key are subset of Super Keys.

Candidate Key

A Candidate Key is a set of one or more fields/columns that can identify a record uniquely in a table. There can be multiple Candidate Keys in one table. Each Candidate Key can work as Primary Key.
Example: In below diagram ID, RollNo and EnrollNo are Candidate Keys since all these three fields can be work as Primary Key.

Primary Key

Primary key is a set of one or more fields/columns of a table that uniquely identify a record in database table. It can not accept null, duplicate values. Only one Candidate Key can be Primary Key.

Alternate key

A Alternate key is a key that can be work as a primary key. Basically it is a candidate key that currently is not primary key.
Example: In below diagram RollNo and EnrollNo becomes Alternate Keys when we define ID as Primary Key.

Composite/Compound Key

Composite Key is a combination of more than one fields/columns of a table. It can be a Candidate key, Primary key.


2. In any table how much primary key is possible?

You can't have several of what is called "primary". The answer is: one. A primary key can contain several columns, though. Then it's what you called a "composite primary key"

3. In a table we can take primary key and foreign key both?
Yes
4. How we make unique key in our database?

CREATE TABLE PersonsUniqueMulti
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
CONSTRAINT uc_PersonID UNIQUE (P_Id,LastName)
ALTER TABLE Persons
ADD CONSTRAINT uc_PersonID UNIQUE (P_Id,LastName
)

5. What is Composite key in our database?

Definition - What does Composite Key mean?
A composite key, in the context of relational databases, is a combination of two or more columns in a table that can be used to uniquely identify each row in the table. Uniqueness is only guaranteed when the columns are combined; when taken individually the columns do not guarantee uniqueness.

6. What is constraint in SQL server?

Constraints let you define the way the Database Engine automatically enforces the integrity of a database. Constraints define rules regarding the values allowed in columns and are the standard mechanism for enforcing integrity. Using constraints is preferred to using DML Triggers, rules, and defaults. The query optimizer also uses constraint definitions to build high-performance query execution plans.




































1. What is the root namespace in C#?

The root namespace is the mainspace of the .NET Framework libraries. It may happen that someone creates a type or a namespace that will conflict with ones from the .NET Framework. In such cases, we can refer to the root namespace with the global:: prefix.

namespace ZetCode
{
    class System 
    {
        public override string ToString() 
        {
            return "This is System class";
        }
    }
 
    public class RootNamespace
    {
        static void Main()
        {
            System s = new System();
            global::System.Console.WriteLine(s); 
        }
    }    
}


2. What is the root class in .Net?

System.object is the root class in .net

Supports all classes in the .NET Framework class hierarchy and provides low-level services to derived classes. This is the ultimate base class of all classes in the .NET Framework; it is the root of the type hierarchy.

Languages typically do not require a class to declare inheritance from Object because the inheritance is implicit.

Because all classes in the .NET Framework are derived from Object, every method defined in the Object class is available in all objects in the system. Derived classes can and do override some of these methods, including:

Equals - Supports comparisons between objects.

Finalize - Performs cleanup operations before an object is automatically reclaimed.

GetHashCode - Generates a number corresponding to the value of the object to support the use of a hash table.

ToString - Manufactures a human-readable text string that describes an instance of the class.


3. What is garbage class and generation number in C#?

4. Why microsoft made MSIL?

In ASP.NET you can write code in many different languages, such as VB, C#, J#, and others. When the code is compiled using its associated compiler, it is translated into a language-independent and CPU-independent representation called Microsoft Intermediate Language (MSIL). At run time, MSIL runs in the context of the .NET Framework, which translates MSIL into CPU-specific instructions for the processor on the computer running that application. Compiling the code improves performance, security, stability and interoperability.

5. How we insert Multiple value in sql insert command?
USE YourDB
GO
INSERT INTO MyTable (FirstCol, SecondCol)
SELECT 'First' ,1
UNION ALL
SELECT 'Second' ,2
UNION ALL
SELECT 'Third' ,3
UNION ALL
SELECT 'Fourth' ,4
UNION ALL
SELECT 'Fifth' ,5
GO
6. Shadowing, Shadowing is possible in C#?

In shadowing, we provide a new implementation to the base class member without overriding it. We may shadow a base class member in a derived class, by using the keyword shadows. The access level, return type, and the signature (means the datatypes of the arguments passed & the order of the types) of the derived class members which are shadowed, may differ from the base class.

In C#, we may achieve shadowing using the keyword new. However, when Hiding in C#, the access level, the signature, return type of the derived class must be same as the base class.













1. What is the difference b/w sql server 2005 and 2008?

There are some differences between both.
 
Sr No
SQL Server 2005
SQL Server 2008
1
XML datatype is introduced.
XML datatype is used.
2
Can not encrypt the entire database.
Can encrypt the entire database introduced in 2008.
3
Datetime is used for both date and time.
Date and time are seperately used for date and time
4
No table datatype is included.
Table datatype introduced.
5
SSIS is started using.
SSIS avails in this version.
6
CMS is not available.
Central Management Server(CMS) is Introduced.
7
PBM is not available
Policy based management(PBM) server is Introduced.


2. What primary key and unique key and difference b/w them?

Primary Key:
i) Can be only one in a table
ii) It never allows null values
iii) Primary Key is unique key identifier and can not be null and must be unique.
Unique Key:
i) Can be more than one unique key in one table.
ii) Unique key can have null values
iii) It can’t be candidate key
iv) Unique key can be null and may not be unique.
3. What stored procedure returns?

If you specify the OUTPUT keyword for a parameter in the procedure definition, the procedure can return the current value of the parameter to the calling program when the procedure exits. To save the value of the parameter in a variable that can be used in the calling program, the calling program must use the OUTPUT keyword when executing the procedure.

Examples of Output Parameter

The following example shows a procedure with an input and an output parameter. The @SalesPerson parameter would receive an input value specified by the calling program. The SELECT statement uses the value passed into the input parameter to obtain the correct SalesYTD value. The SELECT statement also assigns the value to the @SalesYTD output parameter, which returns the value to the calling program when the procedure exits.

5. Can we return dataset through stored procedure?

Yes you can return data from a stored procedure and have it go straight to a
DataSet. SQL Server and Oracle both support this. IMHO I think working
with SQL Server is easier.

SQL Server example -----
Create your stored procedure:
create procedure dbo.MyStoredProcedure
as
begin
select * from Orders
end
GO

6. What is join?

SQL JOIN

An SQL JOIN clause is used to combine rows from two or more tables, based on a common field between them.
The most common type of join is: SQL INNER JOIN (simple join). An SQL INNER JOIN return all rows from multiple tables where the join condition is met.
Let's look at a selection from the "Orders" table:
SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate
FROM Orders
INNER JOIN Customers
ON Orders.CustomerID=Customers.CustomerID;

SQL INNER JOIN Keyword

The INNER JOIN keyword selects all rows from both tables as long as there is a match between the columns in both tables.

SQL INNER JOIN Syntax

SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name=table2.column_name;

SQL LEFT JOIN Keyword

The LEFT JOIN keyword returns all rows from the left table (table1), with the matching rows in the right table (table2). The result is NULL in the right side when there is no match.

SQL LEFT JOIN Syntax

SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name=table2.column_name;

SQL RIGHT JOIN Keyword

The RIGHT JOIN keyword returns all rows from the right table (table2), with the matching rows in the left table (table1). The result is NULL in the left side when there is no match.

SQL RIGHT JOIN Syntax

SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name=table2.column_name;
SQL FULL OUTER JOIN Keyword
The FULL OUTER JOIN keyword returns all rows from the left table (table1) and from the right table (table2).
The FULL OUTER JOIN keyword combines the result of both LEFT and RIGHT joins.

SQL FULL OUTER JOIN Syntax

SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name=table2.column_name;








1. If we write int32=999999999 what error come?

Variable not declared.

2. How we define session [a] for 5 min. and session[b] for 10 min?



3. If we off cookies from our system, system session run or not, where its value save?

Typical session management tasks in a desktop environment include keeping track of which applications are open and which documents each application has opened, so that the same state can be restored when the user logs out and logs in later. For a website, session management might involve requiring the user to re-login if the session has expired (i.e., a certain time limit has passed without user activity). It is also used to store information on the server-side between HTTP requests.

4. What is transation syntax in Sql Server2008?

BEGIN { TRAN | TRANSACTION } 
    [ { transaction_name | @tran_name_variable }
      [ WITH MARK [ 'description' ] ]
    ]
[ ; ]

5. In normal class can we take abstract method?

if you had abstract method on a class that wasn't abstract, that would mean you had a method that cannot be called. But that means the method is not useful, you could remove it and it would all work the same.

6. In interfac if we take 5 methods then we impliment all or not?

All methods in the interface must be implemented within a class.












1.What is the alternative of cursor in sql server?

We can do a WHILE loop, however you should seek to achieve a more set based operation as anything in SQL that is iterative is subject to performance issues.

2. How we use or make dynamic table through table variable?



3. In a function can we select data by temporary table?

Cannot access temporary tables from within a function.

4. We can make a non cluster index by using two column?

It depends. If most of queries are using just one column in the where clause or on join clause. Then single column nc index should be fine.But when you have a combination of columns in where clause then using the combined indexes should be preferred.

5.Can  we access viewstate value from .aspx page to .cs page?

yes

6. What is Sql injection?

SQL injection is a code injection technique that exploits a security vulnerability occurring in the database layer of an application. ....

SQL Injection is one of the many web attack mechanisms used by hackers to steal data from organizations. It is perhaps one of the most common application layer attack techniques used today. It is the type of attack that takes advantage of improper coding of your web applications that allows hacker to inject SQL commands into say a login form to allow them to gain access to the data held within your database.


7. If cookies are disable at browser end does form authentication work?

Forms Authentication can still work as long as you have not set the "cookieless" parameter of the forms element in your web.config file to "UseCookies".
All of the other options, including the default of "UseDeviceProfile", means that FormsAuthentication will work with or without cookies enabled on the browser.
<configuration>
   <system.web>
   <authentication mode="Forms">
      <forms 
      name="MyApp" 
      loginUrl="/login.aspx"
      cookieless="UseDeviceProfile">   // <-- don't set this to "UseCookies" 
      </forms>
   </authentication>
   </system.web>
</configuration>


8. What is session and its mode in Sql Server?
ASP.NET session state enables you to store and retrieve values for a user as the user navigates ASP.NET pages in a Web application.
HTTP is a stateless protocol. This means that a Web server treats each HTTP request for a page as an independent request. The server retains no knowledge of variable values that were used during previous requests. ASP.NET session state identifies requests from the same browser during a limited time window as a session, and provides a way to persist variable values for the duration of that session.

ASP.NET session state supports several different storage options for session data. Each option is identified by a value in the SessionStateMode enumeration. The following list describes the available session state modes:
·         InProc mode, which stores session state in memory on the Web server. This is the default.
·         StateServer mode, which stores session state in a separate process called the ASP.NET state service. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm.
·         SQLServer mode stores session state in a SQL Server database. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm.
·         Custom mode, which enables you to specify a custom storage provider.
·         Off mode, which disables session state.

9. What is caching in .Net?

Caching enables you to store data in memory for rapid access. When the data is accessed again, applications can get the data from the cache instead of retrieving it from the original source. This can improve performance and scalability. In addition, caching makes data available when the data source is temporarily unavailable
 In the .NET Framework 4, the System.Runtime.Caching namespace contains APIs that are designed for both Web and non-Web applications..

10. What is the difference in varchar and nvarchar in Sql server?

varchar DataType

Varchar means variable characters and it is used to store non-unicode characters. It will allocate the memory based on number characters inserted. Suppose if we declared varchar(50) it will allocates memory of 0 characters at the time of declaration. Once we declare varchar(50) and insert only 10 characters of word it will allocate memory for only 10 characters.

nvarchar DataType

nvarchar datatype same as varchar datatype but only difference nvarchar is used to store Unicode characters and it allows you to store multiple languages in database. nvarchar datatype will take twice as much space to store extended set of characters as required by other languages.



































10
1. What is the difference  between layer and tier architecture?
N-layers of application may reside on the same physical computor(same tier) and the components in each layer communicates with the components of other layer by well defined interfaces. Layered architecture focuses on the grouping of related functionality within an application into distinct layers that are stacked vertically on top of each other. Communication between layers is explicit and loosely coupled. With strict layering, components in one layer can interact only with components in the same layer or with components from the layer directly below it.
The main benefits of the layered architectural style are:
Abstraction,Isolation, Manageability, Performance, Reusability, Testability.
N-tier architecture usually has atleast three separate logical parts, each located on separate physical server. Each tier is responsible for a specific functionality. Each tier is completely independent from all other tiers, except for those immediately above and below it. Communication between tiers is typically asynchronous in order to support better scalability.
The main benefits of tier achitecture styles are:
·         Maintainability: Because each tier is independent of the other tiers, updates or changes can be carried out without affecting the application as a whole.
·         Scalability: Because tiers are based on the deployment of layers, scaling out an application is reasonably straightforward.
·         Flexibility: Because each tier can be managed or scaled independently, flexibility is increased.
·         Availability: Applications can exploit the modular architecture of enabling systems using easily scalable components, which increases availability.

In 3 layer architecture, the Database Access Layer (DAL), Business Logic Layer (BLL) and User Interface Layer (UIL) resides as 3 different project and the output of these 3 projects (.dll file) must be together in the same server or on same machinein order for the system to run.However in 3 tier architecture, the Database Access Layer (DAL), Business Logic Layer (BLL) and User Interface Layer (UIL) reside as 3 different projects. But each of the projects can be deployed at the different server or at the different machines and distributed functionality is explored.

2. How we check the state that SP is compiled or not?

If you create any SP, you will find that there is no cache entry for the execution of that SP.
After running the SP for the first time, the entry for the cache is made in the system.


3. What is string and string builder in C#?

string 

1.Its a class used to handle strings. 
2.Here concatenation is used to combine two strings. 
3.String object is used to concatenate two strings. 
4.The first string is combined to the other string by creating a new copy in the memory as a string object, and then the old string is deleted 
5.we say "Strings are immutable". 
6.. system.string is non updatable.
 

stringbuilder 
7.string 
everytime a object has to be created for Operations like 
append,Insert etc. at runtime 

1. system.stringbuilder is updatable. 
2.string builder is faster than the string object. 
3.String builder is more efficient in case large amount of string operations have to be perform. 
4.String builder is mutable means we can able to re size the memory size 
5.Insertion is done on the existing string. 
6.System.stringbuilder is used to dynamic strings 

Example 
class Program 
{ 
static void Main(string[] args) 
{ 
//for example: 
string str = "hello"; //Creates a new object when we concatenate any other words along with str variable it does not actually modify the str variable, instead it creates a whole new string. 
str = str + " to all"; 
Console.WriteLine(str); 
StringBuilder s = new StringBuilder("Hi"); 
s.Append(" To All"); 
Console.WriteLine(s); 
Console.Read(); 
} 
}

4. String a='abc'+'ab' is possible or not?

yes , abcab.

5. Find the nth Maximum Salary of employee?

select MAX(Salary) from Employee;


SELECT MAX(Salary) FROM Employee
WHERE Salary NOT IN (SELECT MAX(Salary) FROM Employee )

select MAX(Salary) from Employee
WHERE Salary <> (select MAX(Salary) from Employee )

SELECT * /*This is the outer query part */
FROM Employee Emp1
WHERE (N-1) = ( /* Subquery starts here */
SELECT COUNT(DISTINCT(Emp2.Salary))
FROM Employee Emp2
WHERE Emp2.Salary > Emp1.Salary)

SELECT TOP 1 Salary
FROM (
      SELECT DISTINCT TOP N Salary
      FROM Employee
      ORDER BY Salary DESC
      ) AS Emp
ORDER BY Salary













1. What is aggregation and assosiation?

Association is a relationship where all object have their own lifecycle and there is no owner. Let’s take an example of Teacher and Student. Multiple students can associate with single teacher and single student can associate with multiple teachers but there is no ownership between the objects and both have their own lifecycle. Both can create and delete independently.
Aggregation is a specialize form of Association where all object have their own lifecycle but there is ownership and child object cannot belongs to another parent object. Let’s take an example of Department and teacher. A single teacher cannot belongs to multiple departments, but if we delete the department teacher object will not destroy. We can think about “has-a” relationship.
Composition is again specialize form of Aggregation and we can call this as a “death” relationship. It is a strong type of Aggregation. Child object dose not have their lifecycle and if parent object deletes all child object will also be deleted. Let’s take again an example of relationship between House and rooms. House can contain multiple rooms there is no independent life of room and any room cannot belongs to two different house if we delete the house room will automatically delete. Let’s take another example relationship between Questions and options. Single questions can have multiple options and option can not belong to multiple questions. If we delete questions options will automatically delete

2. What is Collation in Sql server?

Collation refers to a set of rules that determine how data is sorted and compared. Character data is sorted using rules that define the correct character sequence, with options for specifying case-sensitivity, accent marks, kana character types, and character width.
COLLATE { <collation_name> | database_default }
<collation_name> :: = 
     { Windows_collation_name } | { SQL_collation_name }

4. What is difference between window and server authentication?
Wnidows Authentication 
1.Single User can only login
2.Not Integerated
3.Not Security
SQL SERVER Authentication
1.Multi user can login
2.Integerated
3.More security

5. Life Cycle of Master page?

1.      Content page PreInit event.
2.      Master page controls Init event.
3.      Content controls Init event.
4.      Master page Init event.
5.      Content page Init event.
6.      Content page Load event.
7.      Master page Load event.
8.      Master page controls Load event.
9.      Content page controls Load event.
10.  Content page PreRender event.
11.  Master page PreRender event.
12.  Master page controls PreRender event.
13.  Content page controls PreRender event.
14.  Master page controls Unload event.
15.  Content page controls Unload event.
16.  Master page Unload event.
17.  Content page Unload event.


6. What is Dynamic Sql Query?

Dynamic SQL is a term used to mean SQL code that is generated programatically (in part or fully) by your program before it is executed. As a result it is a very flexible and powerful tool. You can use dynamic SQL to accomplish tasks such as adding where clauses to a search based on what fields are filled out on a form or to create tables with varying names.

7. What is the magic table in Sql Server?
These are Virtual Tables named inserted and updated that are created by SQL Server when we perform an insert, delete or update operation. We can't see the Magic Table directly, We use a trigger to see the Magic Table. 

Type of Magic Table:
  1. Inserted
  2. Deleted




1. What is the difference between abstract class and Interface?
An abstract class can implement methods.
An Interface cannot implement methods. 

An abstract class can inherit from a class and one or more interfaces
An Interface can only inherit from another Interface.. 

An abstract class can contain fields. 
An Interface cannot contain fields.

An abstract class can implement a property. 
An Interface can contain property definitions.

An abstract class can contain constructors or destructors. 
An Interface cannot contain constructors or destructors.

An abstract class cannot be inherited from by structures. 
An Interface can be inherited from by structures.

An abstract class cannot support multiple inheritance. 
An Interface can support multiple inheritance.

2. What is readonly variable?

The readonly keyword is a modifier that you can use on fields. When a field declaration includes a readonly modifier, assignments to the fields introduced by the declaration can only occur as part of the declaration or in a constructor in the same class.
In this example, the value of the field year cannot be changed in the method ChangeYear, even though it is assigned a value in the class constructor:
C#
    class Age
    {
        readonly int _year;
        Age(int year)
        {
            _year = year;
        }
        void ChangeYear()
        {
            //_year = 1967; // Compile error if uncommented.
        }
    }
You can assign a value to a readonly field only in the following contexts:
·         When the variable is initialized in the declaration, for example:
public readonly int y = 5;
·         For an instance field, in the instance constructors of the class that contains the field declaration, or for a static field, in the static constructor of the class that contains the field declaration. These are also the only contexts in which it is valid to pass a readonly field as an out or ref parameter.

3. What is the differnce between Dispose and finalize method?

1. Finalize() belongs to the Object class.
2. It is automatically called by the Garbage Collection mechanism when the object goes out of the scope(usually at the end of the program
3. It is slower method and not suitable for instant disposing of the objects.
4. It is non-deterministic function i.e., it is uncertain when Garbage Collector will call Finalize() method to reclaim memory.
5. Example:

class employee
{
//This is the destructor of emp class
~employee()
{

}
//This destructor is implicitly compiled to the Finalize method.
}

Dispose:

1. Dispose() belongs to the IDisposable interface
2. We have to manually write the code to implement it(User Code)
ex: if we have emp class we have to inherit it from the IDisposable interface
and write code. We may have to suppress the Finalize method using GC.SuppressFinalize() method.
3. Faster method for instant disposal of the objects.
4. It is deterministic function as Dispose() method is explicitly called by the User Code. 

5. Example:

user interface Controls. Forms, SqlConnection class have built in implementaion of Dispose method.

try
{

string constring = "Server=(local);Database=my; User Id=sa; Password=sa";
SqlConnection sqlcon = new SqlConnection(constring);
sqlcon.Open(); // here connection is open


// some code here which will be execute
}
catch
{
// code will be execute when error occurred in try block
}
finally
{
sqlcon.Close(); // close the connection
sqlcon.Dispose(); // detsroy the connection object
}

4. If we create a class how we can call all constructor in only creating one object of class?

Hence does it mean that even if a constructor completes running without any exception, there is no guarantee whether an object is created?
Simply speaking, a constructor does not create an object. It just initializes the state of the object. It's the new operator which creates the object. Now, let's understand this in little detail.
When you create an object using statement like this:
new MyClass();
The object is first created by the new operator. Just before a reference to the newly created object is returned as the result, the indicated constructor is processed to initialize the new object.


Now consider the case of Abstract class and it's concrete SubClass, when you do like this:
AbstractClass obj = new ConcreteClass();
new operator creates an object of ConcreteClass, and invokes its constructor to initialize the state of the created object. In this process, the constructor of the abstract class is also called from theConcreteClass constructor, to initialize the state of the object in the abstract class.
So, basically the object of AbstractClass is not created. It's just that it's constructor is invoked to initialize the state of the object.
Lessons Learnt:
·         The object is created by new operator, and not by the invocation of the constructor     itself. So, the object is already created before any constructor is invoked.
·         Constructor is just used to initialize the state of the object created. It does not create an object itself.
·         An object state can also be contained in an abstract super class.
·         So, the purpose of invocation of Abstract class constructor, is only to initialize the object completely, and no object is created in process.



No comments:

Post a Comment