Saturday, January 31, 2009

SQL, PL/SQL FAQs

SQL, PL/SQL FAQ

About Triggers:

1. What are triggers? What are the different types of triggers?
A Database Trigger is a stored procedure that is fired when a DML operation is performed on the table. In total there are 13 types of Triggers
Syntax for creating a trigger:
CREATE OR REPLACE TRIGGER [triggername]before / after
[INSERT / UPDATE / DELTE] ON [tablename]
{For each Statement / Row}
{When }
Types of Triggers:
Before
After
For each Row
For each Statement (default)
Instead of Trigger: This trigger is defined on a view rather than a table.

System Triggers: A new feature of Oracle8i, wherein the trigger is fired when the database startup / shutdown process.

Schema Triggers: These triggers are fired whenever a DDL statement is executed. (Creation or Deletion of any DB Objects)

Order of Trigger Firing:
· Before Statement trigger (If present)
· Each row affected by the statement
(a) Execute row level trigger (If present)
(b) Execute the statement itself
(c) Execute the after row level trigger (If Present)
· After statement trigger (If Present)

2. What are the different types of joins available in Oracle?
Equi Join: When primary and foreign key relationship exists between the tables that are going to be joined.
Self Join: If comparison comes in a single table
Cartesian Join: When tables are joined without giving any join condition.
Inner Join: The resultant set includes all the rows that satisfy the join condition.
Outer Join: The resultant set includes the rows which doesn’t satisfy the join condition. The outer join operator Plus sign (+) will be included in the join condition.
Example: SELECT a. column1, a. column2, b.column3….. From a, b where
a.column1 (+) =b.Column1
Here the rows from table ‘a’ which doesn’t satisfy the join condition will also be fetched.


3. What are Indexes? What are the different types of Index? If a table consists of more than one Index how to enforce the statement to use the second Index?
An Index is a DB object, which is used to improve the performance of the data retrieval.
CREATE INDEX [IndexName]ON [tablename].([columnname])
Types of Indexes:
Bitmap Index (Used for Low cardinality column)
Btree Index (Used for high cardinality column)

4. What is Mutating Table?
Table under transition is called Mutating Table.

5. What is a view? What is Inline View??
Views are window to a table. It contains no data; it is based on the actual table called the base table or a view.
Inline View means writing select statement in the Query itself instead of selecting a Column Name.

What is a Cursor? When it is used? What are different types of Cursors?
Cursor is a private SQL area created in SGA (system global area) to do multi row operation in a PL/SQL program
Explicit Cursor, Implicit Cursor.
Implicit Cursor: System (Oracle) automatically declares and uses for all DML SQL Statements.
Explicit Cursor: Cursor declared explicitly in the PL/SQL program to do multi row operation
Syntax:
Declare
Cursor C1 is SELECT SAL, EMPNO FROM EMP
X number;
Y Varchar2 (30);
Begin
Open C1;
Loop
Fetch C1 INTO x, y;
Exit when c1%NOTFOUND
End Loop;
End;

What is for Cursor? When it is used? Is it necessary to write an explicit exit in case for Cursor?
A Cursor for loop can be used to simplify the explicit cursor, no need to explicitly open, fetch and close. No explicit EXIT statement is required.

What are Cursor attributes? What is use of FOR UPDATE in Cursor?
%Found
%NotFound
%RowCount
%IsOpen

FOR UPDATE statement in Cursor is used to update a Column in the selected table by using the CURRENT OF .

What is a Package? What is the advantage of using Packages?
A Package is a PL/SQL Construct that allows related objects to be stored together. Package contains 2 parts, Package Specification and Package Body, each stored separately in the Data Dictionary.
Once the Package is called all the related Procedure and functions of the package gets compiled and stored in the memory as P-code.
How does u call a Package?
. (Related Parameters….)

Name some important Packages provided by Oracle?
DBMS_SQL, DBMS_JOBS, DBMS_DDL, DBMS_LOCK

What is Overloading?
Overloading is oops concept (Object Oriented Programming)
By Using the same name we can write any number of Procedure or functions in a package but either number of parameters in the procedure/function must be vary or parameter data type must vary.

What is a Function? Difference between Procedure and Function?
Function is an object that takes one or more arguments and returns only value. But in case of procedures we can return more than one parameters.
Function always returns a value, whereas procedure may or may not return a value.


What is the Package used in Oracle to do the File Operation?
UTL_FILE

What is Dynamic SQL? How Dynamic SQL can be built?
The SQL statements which are built at run time are called the Dynamic SQL. Dynamic SQL can be built by using DBMS_SQL package.
Procedure of Dynamic SQL
OPEN_CURSOR, PARSE, BIND_VARIABLE, DEFINE_COLUMN, EXECUTE, FETCH_ROWS, CLOSE_CURSOR.
Oracle8i onwards there is another built-in to construct Dynamic SQL called EXECUTE_IMMEDIATE.


What is an exception? What are the different types of Exception? How does u declare a user defined exception?
The error condition in PL/SQL is termed as an exception. Two types of
Exception:
Pre-Defined Exception: Example No_Data_Found, Storage_Error,
Zero_Error, Invalid_Cursor, Too_Many_Rows
User-Defined Exception: Anything

Syntax:
Declare
Xyz Exception;
Begin
SELECT ENAME FROM EMP
RAISE XYZ;
End;

what could happen if we use WHEN OTHERS before any predefined exceptions
According to the Oracle standards “When Others” exception must be the last exception. All the Pre-defined exceptions must be used before the “When others” exception.
If “When others” exception used before any pre-defined exceptions then procedure/function shows the compilations errors

List out some features in 8i.
Bitmap Indexes, Drop a Column, Bulk Insert and Bulk Update
Materialized views, Dynamic Sql (Execute Immediate etc)

List some 9i features
External tables (We query the data directly from a file like select * from “c:/abcd.csv”)
Multi Table Insert with single command, resumable process etc.

What are SQLCODE and SQLERRM and why are they important for PL/SQL developers?

SQLCODE returns the value of the error number for the last error encountered. The SQLERRM returns the actual error message for the last error encountered. They can be used in exception handling to report, or, store in an error log table, the error that occurred in the code. These are especially useful for the WHEN OTHERS exception

What is the use of Pragma_Init exception?
By using this we can define our messages by handling the oracle messages

What are temporary tables? How many types?
Temporary tables are used to store the data temporarily. Mainly there are 2 types
They are transaction and Session types
Syntax: Create global temporary table as select * from emp;
This temporarly table is used to store the data temporarily, and once you exit from session then that table will get erased.

Some of the System Tables
a. User_source table will stores the information of the user defined definitions
b. All_Source and dba_source tables will stores the system defined schema objects definitions as well as user defined.
c. All_Tab_Columns and ben_all_tab_columns are used to list out the all the columns name and respected table names also.

23. Write a query to list out the employees with their respective manager levels?

select lpad ('*', level * 2), empno, ename, mgr from emp
connect by prior empno = mgr start with empno = 7839
It results the hierarchy of the employees
Note: For Answers Check the Next Page

* What is PL/SQL and what is it used for?
* Should one use PL/SQL or Java to code procedures and triggers?
* How can one see if somebody modified any code?
* How can one search PL/SQL code for a key?
* How can one keep a history of PL/SQL code changes?
* How can I protect my PL/SQL source code?
* Can one print to the screen from PL/SQL?
* Can one read/write files from PL/SQL?
* Can one call DDL statements from PL/SQL?
* Can one use dynamic SQL statements from PL/SQL?
* What is the difference between %TYPE and %ROWTYPE?
* How does one get the value of a sequence into a PL/SQL variable?
* Can one execute an operating system command from PL/SQL?
* How does one loop through tables in PL/SQL?
* How often should one COMMIT in a PL/SQL loop? / What is the best commit strategy?
* I can SELECT from SQL*Plus but not from PL/SQL. What is wrong?
* What is a mutating and constraining table?
* Can one pass an object/table as an argument to a remote procedure?
* Is it better to put code in triggers or procedures? What is the difference?
* Is there a PL/SQL Engine in SQL*Plus?
* Is there a limit on the size of a PL/SQL block?
* Where can one find more info about PL/SQL?

What is PL/SQL and what is it used for?

PL/SQL is Oracle's Procedural Language extension to SQL. PL/SQL's language syntax, structure and data types are similar to that of ADA. The PL/SQL language includes object oriented programming techniques such as encapsulation, function overloading, and information hiding (all but inheritance). PL/SQL is commonly used to write data-centric programs to manipulate data in an Oracle database.

Should one use PL/SQL or Java to code procedures and triggers?

Internally the Oracle database supports two procedural languages, namely PL/SQL and Java. This leads to questions like "Which of the two is the best?" and "Will Oracle ever de-support PL/SQL in favor of Java?”
Many Oracle applications are based on PL/SQL and it would be difficult of Oracle to ever de-support PL/SQL. In fact, all indications are that PL/SQL still has a bright future ahead of it. Many enhancements are still being made to PL/SQL. For example, Oracle 9iDB supports native compilation of Pl/SQL code to binaries.

PL/SQL and Java appeal to different people in different job roles. The following table briefly describes the difference between these two language environments:

PL/SQL:

Data centric and tightly integrated into the database
Proprietary to Oracle and difficult to port to other database systems
Data manipulation is slightly faster in PL/SQL than in Java
Easier to use than Java (depending on your background)
Java:

Open standard, not proprietary to Oracle
Incurs some data conversion overhead between the Database and Java type systems
Java is more difficult to use (depending on your background)

How can one see if somebody modified any code?

Code for stored procedures, functions and packages is stored in the Oracle Data Dictionary. One can detect code changes by looking at the LAST_DDL_TIME column in the USER_OBJECTS dictionary view. Example:
SELECT OBJECT_NAME,
TO_CHAR (CREATED, 'DD-Mon-RR HH24:MI') CREATE_TIME,
TO_CHAR (LAST_DDL_TIME, 'DD-Mon-RR HH24:MI') MOD_TIME,
STATUS
FROM USER_OBJECTS
WHERE LAST_DDL_TIME > '&CHECK_FROM_DATE';

How can one search PL/SQL code for a key?

The following query is handy if you want to know where a certain table, field or expression is referenced in your PL/SQL source code.
SELECT TYPE, NAME, LINE
FROM USER_SOURCE
WHERE UPPER (TEXT) LIKE '%&KEYWORD%';

* By using DBA_DEPENDENCIES table you can find out. - Ezhil

How can one keep a history of PL/SQL code changes?

One can build a history of PL/SQL code changes by setting up an AFTER CREATE schema (or database) level trigger (available from Oracle 8.1.7). This way one can easily revert to previous code, should someone make any catastrophic changes? Look at this example:
CREATE TABLE SOURCE_HIST -- Create history table
AS SELECT SYSDATE CHANGE_DATE, USER_SOURCE.*
FROM USER_SOURCE WHERE 1=2;

CREATE OR REPLACE TRIGGER change_hist -- Store code in hist table
AFTER CREATE ON SCOTT.SCHEMA -- Change SCOTT to your schema name
DECLARE
BEGIN
If DICTIONARY_OBJ_TYPE in ('PROCEDURE', 'FUNCTION',
'PACKAGE', 'PACKAGE BODY', 'TYPE') then
-- Store old code in SOURCE_HIST table
INSERT INTO SOURCE_HIST
SELECT sysdate, user_source.* FROM USER_SOURCE
WHERE TYPE = DICTIONARY_OBJ_TYPE
AND NAME = DICTIONARY_OBJ_NAME;
End if;
EXCEPTION
WHEN OTHERS THEN
raise_application_error (-20000, SQLERRM);
END;
/
Show errors

How can I protect my PL/SQL source code?

PL/SQL V2.2, available with Oracle7.2, implements a binary wrapper for PL/SQL programs to protect the source code.
This is done via a standalone utility that transforms the PL/SQL source code into portable binary object code (somewhat larger than the original). This way you can distribute software without having to worry about exposing your proprietary algorithms and methods. SQL*Plus and SQL*DBA will still understand and know how to execute such scripts. Just be careful, there is no "decode" command available.

The syntax is:

Wrap iname=myscript.sql oname=xxxx.plb


Can one print to the screen from PL/SQL?

One can use the DBMS_OUTPUT package to write information to an output buffer. This buffer can be displayed on the screen from SQL*Plus if you issue the SET SERVEROUTPUT ON; command. For example:
Set serveroutput on

Begin
dbms_output.put_line ('Look Ma, I can print from PL/SQL!!!');
End;
/

DBMS_OUTPUT is useful for debugging PL/SQL programs. However, if you print too much, the output buffer will overflow. In that case, set the buffer size to a larger value, e.g.: set serveroutput on size 200000

If you forget to set serveroutput on type SET SERVEROUTPUT ON once you remember, and then EXEC NULL;. If you haven't cleared the DBMS_OUTPUT buffer with the disable or enable procedure, SQL*Plus will display the entire contents of the buffer when it executes this dummy PL/SQL block.


Can one read/write files from PL/SQL?

Included in Oracle 7.3 is an UTL_FILE package that can read and write operating system files. The directory you intend writing to has to be in your INIT.ORA file (see UTL_FILE_DIR=... parameter). Before Oracle 7.3 the only means of writing a file was to use DBMS_OUTPUT with the SQL*Plus SPOOL command.
Copy this example to get started:

DECLARE
File Handler UTL_FILE.FILE_TYPE;
BEGIN
File Handler: = UTL_FILE.FOPEN ('/tmp', 'myfile', 'w');
UTL_FILE.PUTF (fileHandler, 'Look ma, I'm writing to a file!!!\n');
UTL_FILE.FCLOSE (fileHandler);
EXCEPTION
WHEN utl_file.invalid_path THEN
raise_application_error (-20000, 'ERROR: Invalid path for file or path not in INIT.ORA.');
END;
/

Can one call DDL statements from PL/SQL?

One can call DDL statements like CREATE, DROP, TRUNCATE, etc. from PL/SQL by using the "EXECUTE IMMEDATE" statement. Users running Oracle versions below 8i can look at the DBMS_SQL package (see FAQ about Dynamic SQL).
Begin
EXECUTE IMMEDIATE 'CREATE TABLE X (A DATE)';
End;

NOTE: The DDL statement in quotes should not be terminated with a semicolon.

Can one use dynamic SQL statements from PL/SQL?

From PL/SQL V2.1 one can use the DBMS_SQL package to execute dynamic SQL statements. E.g.:
CREATE OR REPLACE PROCEDURE DYNSQL AS
cur integer;
rc integer;
BEGIN
Cur: = DBMS_SQL.OPEN_CURSOR;
DBMS_SQL.PARSE (cur, 'CREATE TABLE X (Y DATE)', DBMS_SQL.NATIVE);
RC: = DBMS_SQL.EXECUTE (cur);
DBMS_SQL.CLOSE_CURSOR (cur);
END;
/

Another example:
CREATE OR REPLACE PROCEDURE DEPARTMENTS(NO IN DEPT.DEPTNO%TYPE) AS
v_cursor integer;
v_dname char(20);
v_rows integer;
BEGIN
v_cursor := DBMS_SQL.OPEN_CURSOR;
DBMS_SQL.PARSE(v_cursor, 'select dname from dept where deptno > :x', DBMS_SQL.V7);
DBMS_SQL.BIND_VARIABLE(v_cursor, ':x', no);
DBMS_SQL.DEFINE_COLUMN_CHAR(v_cursor, 1, v_dname, 20);
v_rows := DBMS_SQL.EXECUTE(v_cursor);
loop
if DBMS_SQL.FETCH_ROWS(v_cursor) = 0 then
exit;
end if;
DBMS_SQL.COLUMN_VALUE_CHAR(v_cursor, 1, v_dname);
DBMS_OUTPUT.PUT_LINE('Deptartment name: 'v_dname);
end loop;
DBMS_SQL.CLOSE_CURSOR(v_cursor);
EXCEPTION
when others then
DBMS_SQL.CLOSE_CURSOR(v_cursor);
raise_application_error(-20000, 'Unknown Exception Raised: 'sqlcode' 'sqlerrm);
END;
/

What is the difference between %TYPE and %ROWTYPE?

The %TYPE and %ROWTYPE constructs provide data independence, reduces maintenance costs, and allows programs to adapt as the database changes to meet new business needs.
%ROWTYPE is used to declare a record with the same types as found in the specified database table, view or cursor. Example:

DECLARE
v_EmpRecord emp%ROWTYPE;
%TYPE is used to declare a field with the same type as that of a specified table's column. Example:

DECLARE
v_EmpNo emp.empno%TYPE;

How does one get the value of a sequence into a PL/SQL variable?

As you might know, oracle prohibits this:
i := sq_sequence.NEXTVAL;
(for some silly reason). But you can do this:
select sq_sequence.NEXTVAL into :i from dual;
Thanks to Ronald van Woensel

Can one execute an operating system command from PL/SQL?

There is no direct way to execute operating system commands from PL/SQL in Oracle7. However, one can write an external program (using one of the precompiler languages, OCI or Perl with Oracle access modules) to act as a listener on a database pipe (SYS.DBMS_PIPE). Your PL/SQL program then put requests to run commands in the pipe, the listener picks it up and run the requests. Results are passed back on a different database pipe. For an Pro*C example, see chapter 8 of the Oracle Application Developers Guide.
In Oracle8 one can call external 3GL code in a dynamically linked library (DLL or shared object). One just write a library in C/ C++ to do whatever is required. Defining this C/C++ function to PL/SQL makes it executable. Look at this External Procedure example.


How does one loop through tables in PL/SQL?

Look at the following nested loop code example.
DECLARE
CURSOR dept_cur IS
SELECT deptno
FROM dept
ORDER BY deptno;
-- Employee cursor all employees for a dept number
CURSOR emp_cur (v_dept_no DEPT.DEPTNO%TYPE) IS
SELECT ename
FROM emp
WHERE deptno = v_dept_no;
BEGIN
FOR dept_rec IN dept_cur LOOP
dbms_output.put_line('Employees in Department 'TO_CHAR(dept_rec.deptno));
FOR emp_rec in emp_cur(dept_rec.deptno) LOOP
dbms_output.put_line('...Employee is 'emp_rec.ename);
END LOOP;
END LOOP;
END;
/

How often should one COMMIT in a PL/SQL loop? / What is the best commit strategy?

Contrary to popular believe, one should COMMIT less frequently within a PL/SQL loop to prevent ORA-1555 (Snapshot too old) errors. The higher the frequency of commit, the sooner the extents in the rollback segments will be cleared for new transactions, causing ORA-1555 errors.
To fix this problem one can easily rewrite code like this:

FOR records IN my_cursor LOOP
...do some stuff...
COMMIT;
END LOOP;

... to ...
FOR records IN my_cursor LOOP
...do some stuff...
i := i+1;
IF mod(i, 10000) THEN -- Commit every 10000 records
COMMIT;
END IF;
END LOOP;

If you still get ORA-1555 errors, contact your DBA to increase the rollback segments.
NOTE: Although fetching across COMMITs work with Oracle, is not supported by the ANSI standard.

I can SELECT from SQL*Plus but not from PL/SQL. What is wrong?

PL/SQL respect object privileges given directly to the user, but does not observe privileges given through roles. The consequence is that a SQL statement can work in SQL*Plus, but will give an error in PL/SQL. Choose one of the following solutions:
Grant direct access on the tables to your user. Do not use roles!
GRANT select ON scott.emp TO my_user;

Define your procedures with invoker rights (Oracle 8i and higher);

Move all the tables to one user/schema.

What is a mutating and constraining table?

"Mutating" means "changing". A mutating table is a table that is currently being modified by an update, delete, or insert statement. When a trigger tries to reference a table that is in state of flux (being changed), it is considered "mutating" and raises an error since Oracle should not return data that has not yet reached its final state.
Another way this error can occur is if the trigger has statements to change the primary, foreign or unique key columns of the table off which it fires. If you must have triggers on tables that have referential constraints, the workaround is to enforce the referential integrity through triggers as well.

There are several restrictions in Oracle regarding triggers:

A row-level trigger cannot query or modify a mutating table. (Of course, NEW and OLD still can be accessed by the trigger) .
A statement-level trigger cannot query or modify a mutating table if the trigger is fired as the result of a CASCADE delete.
Etc.

Can one pass an object/table as an argument to a remote procedure?

The only way the same object type can be referenced between two databases is via a database link. Note that it is not enough to just use the same type definitions. Look at this example:
-- Database A: receives a PL/SQL table from database B
CREATE OR REPLACE PROCEDURE pcalled(TabX DBMS_SQL.VARCHAR2S) IS
BEGIN
-- do something with TabX from database B
null;
END;
/

-- Database B: sends a PL/SQL table to database A
CREATE OR REPLACE PROCEDURE pcalling IS
TabX DBMS_SQL.VARCHAR2S@DBLINK2;
BEGIN
pcalled@DBLINK2 (TabX);
END;
/

Is it better to put code in triggers or procedures? What is the difference?

In earlier releases of Oracle it was better to put as much code as possible in procedures rather than triggers. At that stage procedures executed faster than triggers as triggers had to be re-compiled every time before executed (unless cached). In more recent releases both triggers and procedures are compiled when created (stored p-code) and one can add as much code as one likes in either procedures or triggers.

Is there a PL/SQL Engine in SQL*Plus?

No. Unlike Oracle Forms, SQL*Plus does not have a PL/SQL engine. Thus, all your PL/SQL is sent directly to the database engine for execution. This makes it much more efficient as SQL statements are not stripped off and sent to the database individually.

Is there a limit on the size of a PL/SQL block?
Yes, the max size is not an explicit byte limit, but related to the parse tree that is created when you compile the code. You can run the following select statement to query the size of an existing package or procedure:
SQL> select * from dba_object_size where name = 'procedure_name';




Forms/Reports

1. How you declare global variables in forms ?
Global variable will declared in When-New-Form-Instance Triggers

2. What are Table Handlers and Event Handlers?

3. What are new feature in forms 6i compared to forms4.5

4.What is the Difference between callform, Newform, Openform

5.What is the Use of Program Units in form/reports ?

6.How many triggers is there in reports and what are they and what is the Order of firing
Before Parameter Form
After Parameter Form
Before report
Between pages
After Report

7. Which trigger will get fired while opening an LOV in forms?
Key-List-Value

8. How Many Types of reports are there? Name it??

9. What is the Use of Anchors in Reports?

10. What are the uses and differences between Summary Column, Formula column and Place holder column?

11. What is the Difference between Bind parameter and lexical parameter? Which trigger will be used to specify the conditions for a lexical parameter?

12. What is the use of Destype, Desname, Desformat in Parameter form.

13. When the Between Pages Trigger will fire?
After first page this trigger will fire until last
page and after that for last page it wont fire.


14. What are the forms Modules?
They are 4 types of form modules are there 1) Alerts 2) Forms Modules 3) Menu
Modules 4) PLSQL Libraries

15. Some of the New Features in Reports6i
In 6i we can generate the report in different types like PDF, HTML XML, and RTF etc
In reports goto -> Layout model à Header or Body or Margin sections à property
Pallateà Distributions. Specify the Type and file name with path.
Then gotoà File à Distribute

16. What is the difference between Format Triggers and Action Triggers?
Action Trigger is Procedure whereas Format Trigger is Procedure
By using Action trigger we can open the other form or report

17 What is the Difference between Flex Mode and Confine Mode and their differences?

18. What is the Order of triggers firing?
W-N-F-I, Pre-Form, W-N-I-I, W-N-B-I??

19 What is the Major Differences and uses between Property Class and Visual Attribute

20. Other than Run_Product how can we run a report from a form
By using Run_Report_Object function we can run the reports ( This is 6i New Feature)
To use this Add that report in Form Object Navigator and pass the Id of that report.

21. What are the Default triggers will be created when a master-detail form is created
There are 3 types are triggers will be created in form level when a master-detail form is created.
22. What is the Difference between .pll, .pls and .plx in Libraries?

23. What are Object Library and Attached Library?
Object Library can be used to stored Function, Procedure, Package. Attached library will be used to avoid any change in source code. Object library can be converted into .PLX and attached to Attached library.

24. What is the difference between writing code in Programme Unit and Library Files?
The code written in Programme unit is form’s specific, whereas code written in
Library files can be used across the forms.

25. When a form is run, which are the triggers fire, and in what sequence they fire?
PRE-FORM
WHEN-NEW-FORM-INSTANCE
PRE-BLOCK
WHEN-NEW-BLOCK-INSTANCE
WHEN-NEW-ITEM-INSTANCE
POST-BLOCK
POST-FORM

1. What is the difference between Forms 4.5 and Forms 6i
Tab Page utility is not available in 4.5 Version

2. What is the utility used to call the report from the forms?
RUN_REPORT

3. What is a Property Class? Different methods of creating property class?
Property Class is defining properties of objects along with their settings. The property class inheritance allows the user to perform global changes very quickly and efficiently.
Methods:
Object Navigator Method
Properties Window Method

4. WHEN-NEW-FORM trigger written at Form Level, Block Level and Item Level which one will fire first?
The trigger written at the lower level Item Level Fires first then at Block Level and at last it fires in Form Level.

5. In the previous question circumstance, is it possible to change the order of trigger Execution? If yes, where it needs to be changed?
Yes, in the trigger property (Before, After, Default)by changing the attributes.

6. What are the different kinds of Parameters available in the report?
System and User defined Parameters.(Bind and Lexical Parameters)

Friday, January 30, 2009

C#.Net Material



Download Links:

1. Apress-beginning-Csharp-2008-from-novice-to-Professional-nov2007

2. Wordware-learn-Csharp-includes-the-Csharp-30Features-aug2007-Material

3. Sharp-Develop-Coding-Style-03

4. Csharp-Programming

ASP.NET FAQs-1

1. Describe the role of inetinfo.exe, aspnet_isapi.dll andaspnet_wp.exe in the page loading process.
inetinfo.exe is the Microsoft IIS server running, handling ASP.NET requests among other things. When an ASP.NET request is received (usually a file with .aspx extension),the ISAPI filter aspnet_isapi.dll takes care of it by passing the request to the actual worker process aspnet_wp.exe.
2. What’s the difference between Response.Write() and Response.Output.Write()?
The latter one allows you to write formatted output.
3. What methods are fired during the page load?
Init() - when the page is instantiated, Load() - when the page is loaded into server memory, PreRender() - the brief moment before the page is displayed to the user as HTML, Unload() - when page finishes loading.
4. Where does the Web page belong in the .NET Framework class hierarchy? System.Web.UI.Page
5. Where do you store the information about the user’s locale?
System.Web.UI.Page.Culture
6. What’s the difference between Codebehind="MyCode.aspx.cs" and Src="MyCode.aspx.cs"? CodeBehind is relevant to Visual Studio.NET only.
7. What’s a bubbled event?
When you have a complex control, like DataGrid, writing an event processing routine for each object (cell, button, row, etc.) is quite tedious. The controls can bubble up their event handlers, allowing the main DataGrid event handler to take care of its constituents.
8. Suppose you want a certain ASP.NET function executed on MouseOver a certain button. Where do you add an event handler?
It’s the Attributes property, the Add function inside that property. So btnSubmit.Attributes.Add("onMouseOver","someClientCode();")
9. What data type does the Range Validator control support?
Integer, String and Date.
10. Explain the differences between Server-side and Client-side code?
Server-side code runs on the server. Client-side code runs in the clients’ browser.
11. What type of code (server or client) is found in a Code-Behind class?
Server-side code.
12. Should validation (did the user enter a real date) occur server-side or client-side? Why? Client-side. This reduces an additional request to the server to validate the users input.
13. What does the "Enable ViewState" property do? Why would I want it on or off?
It enables the viewstate on the page. It allows the page to save the users input on a form.
14. What is the difference between Server.Transfer and Response.Redirect? Why would I choose one over the other?
Server.Transfer is used to post a form to another page. Response.Redirect is used to redirect the user to another page or site.
15. Can you explain the difference between an ADO.NET Dataset and an ADO Recordset?
· A DataSet can represent an entire relational database in memory, complete with tables, relations, and views.
· A DataSet is designed to work without any continuing connection to the original data source.
· Data in a DataSet is bulk-loaded, rather than being loaded on demand.
· There's no concept of cursor types in a DataSet.
· DataSets have no current record pointer You can use For Each loops to move through the data.
· You can store many edits in a DataSet, and write them to the original data source in a single operation.
· Though the DataSet is universal, other objects in ADO.NET come in different versions for different data sources.
16. Can you give an example of what might be best suited to place in the Application_Start and Session_Start subroutines?
This is where you can set the specific variables for the Application and Session objects.
17. If I’m developing an application that must accommodate multiple security levels though secure login and my ASP.NET web application is spanned across three web-servers (using round-robin load balancing) what would be the best approach to maintain login-in state for the users?
Maintain the login state security through a database.
18. Can you explain what inheritance is and an example of when you might use it?
When you want to inherit (use the functionality of) another class. Base Class Employee. A Manager class could be derived from the Employee base class.
19. Whats an assembly?
Assemblies are the building blocks of the .NET framework. Overview of assemblies from MSDN
20. Describe the difference between inline and code behind.
Inline code written along side the html in a page. Code-behind is code written in a separate file and referenced by the .aspx page.
21. Explain what a diffgram is, and a good use for one?
The DiffGram is one of the two XML formats that you can use to render DataSet object contents to XML. For reading database data to an XML file to be sent to a Web Service.
22. Whats MSIL, and why should my developers need an appreciation of it if at all?
MSIL is the Microsoft Intermediate Language. All .NET compatible languages will get converted to MSIL.
23. Which method do you invoke on the DataAdapter control to load your generated dataset with data?
The .Fill() method
24. Can you edit data in the Repeater control?
No, it just reads the information from its data source
25. Which template must you provide, in order to display data in a Repeater control? ItemTemplate
26. How can you provide an alternating color scheme in a Repeater control?
Use the AlternatingItemTemplate
27. What property must you set, and what method must you call in your code, in order to bind the data from some data source to the Repeater control?
You must set the DataSource property and call the DataBind method.
28. What base class do all Web Forms inherit from?
The Page class.
29. Name two properties common in every validation control?
ControlToValidate property and Text property.
30. What tags do you need to add within the asp:datagrid tags to bind columns manually?
Set AutoGenerateColumns Property to false on the datagrid tag
31. What tag do you use to add a hyperlink column to the DataGrid?
32. What is the transport protocol you use to call a Web service?

SOAP is the preferred protocol.
33. True or False: A Web service can only be written in .NET?

False
34. What does WSDL stand for?

(Web Services Description Language)
35. Where on the Internet would you look for Web services?

(http://www.uddi.org/)
36. Which property on a Combo Box do you set with a column name, prior to setting the DataSource, to display data in the combo box?

DataTextField property
37. Which control would you use if you needed to make sure the values in two different controls matched?

CompareValidator Control
38. True or False: To test a Web service you must create a windows application or Web application to consume this service?

False, the webservice comes with a test page and it provides HTTP-GET method to test.
39. How many classes can a single .NET DLL contain?

It can contain many classes.

.NET Remoting Q&A

1.What’s a Windows process?
It’s an application that’s running and had been allocated memory.
2.What’s typical about a Windows process in regards to memory allocation?
Each process is allocated its own block of available RAM space, no process can access another process’ code or data. If the process crashes, it dies alone without taking the entire OS or a bunch of other applications down.
3.Why do you call it a process? What’s different between process and application in .NET, not common computer usage, terminology?
A process is an instance of a running application. An application is an executable on the hard drive or network. There can be numerous processes launched of the same application (5 copies of Word running), but 1 process can run just 1 application.
4.What distributed process frameworks outside .NET do you know?
Distributed Computing Environment/Remote Procedure Calls (DEC/RPC), Microsoft Distributed Component Object Model (DCOM), Common Object Request Broker Architecture (CORBA), and Java Remote Method Invocation (RMI).
5.What are possible implementations of distributed applications in .NET?
.NET Remoting and ASP.NET Web Services. If we talk about the Framework Class Library, noteworthy classes are in System.Runtime.Remoting and System.Web.Services.
6.When would you use .NET Remoting and when Web services?
Use remoting for more efficient exchange of information when you control both ends of the application. Use Web services for open-protocol-based information exchange when you are just a client or a server with the other end belonging to someone else.
7.What’s a proxy of the server object in .NET Remoting?
It’s a fake copy of the server object that resides on the client side and behaves as if it was the server. It handles the communication between real server object and the client object. This process is also known as marshaling.
8.What are remotable objects in .NET Remoting?
Remotable objects are the objects that can be marshaled across the application domains. You can marshal by value, where a deep copy of the object is created and then passed to the receiver. You can also marshal by reference, where just a reference to an existing object is passed.
9.What are channels in .NET Remoting?
Channels represent the objects that transfer the other serialized objects from one application domain to another and from one computer to another, as well as one process to another on the same box. A channel must exist before an object can be transferred.
10.What security measures exist for .NET Remoting in System.Runtime.Remoting?
None. Security should be taken care of at the application level. Cryptography and other security techniques can be applied at application or server level.
11.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.
12.Choosing between HTTP and TCP for protocols and Binary and SOAP for formatters, what are the trade-offs?
Binary over TCP is the most effiecient, SOAP over HTTP is the most interoperable.
13.What’s SingleCall activation mode used for?
If the server object is instantiated for responding to just one single request, the request should be made in SingleCall mode.
14.What’s Singleton activation mode?
A single object is instantiated regardless of the number of clients accessing it. Lifetime of this object is determined by lifetime lease.
15.How do you define the lease of the object?
By implementing ILease interface when writing the class code.
16.Can you configure a .NET Remoting object via XML file?
Yes, via machine.config and application level .config file (or web.config in ASP.NET). Application-level XML settings take precedence over machine.config.
17.How can you automatically generate interface for the remotable object in .NET with Microsoft tools?
Use the Soapsuds tool.

C# FAQs-4

1. Does C# support multiple-inheritance?
No.

2. Who is a protected class-level variable available to?
It is available to any sub-class (a class inheriting this class).

3. Are private class-level variables inherited?
Yes, but they are not accessible. Although they are not visible or accessible via the class interface, they are inherited.

4. Describe the accessibility modifier “protected internal”.
It is available to classes that are within the same assembly and derived from the specified base class.

5. What’s the top .NET class that everything is derived from?
System.Object.

6. What does the term immutable mean?
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.

7. What’s the difference between System.String and System.Text.StringBuilder classes?
System.String is immutable. System.StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed.

8. What’s the advantage of using System.Text.StringBuilder over System.String?
StringBuilder is more efficient in cases where there is a large amount of string manipulation. Strings are immutable, so each time a string is changed, a new instance in memory is created.

9. Can you store multiple data types in System.Array?
No.

10. What’s the difference between the System.Array.CopyTo() and System.Array.Clone()?
The Clone() method returns a new array (a shallow copy) object containing all the elements in the original array. The CopyTo() method copies the elements into another existing array. Both perform a shallow copy. A shallow copy means the contents (each array element) contains references to the same object as the elements in the original array. A deep copy (which neither of these methods performs) would create a new instance of each element's object, resulting in a different, yet identacle object.

11. How can you sort the elements of the array in descending order?
By calling Sort() and then Reverse() methods.

12. What’s the .NET collection class that allows an element to be accessed using a unique key?
HashTable.

13. What class is underneath the SortedList class?
A sorted HashTable.

14. Will the finally block get executed if an exception has not occurred?¬
Yes.

15. What’s the C# syntax to catch any possible exception?
A catch block that catches the exception of type System.Exception. You can also omit the parameter data type in this case and just write catch {}.

16. Can multiple catch blocks be executed for a single try statement?
No. Once the proper catch block processed, control is transferred to the finally block (if there are any).

17. Explain the three services model commonly know as a three-tier application.
Presentation (UI), Business (logic and underlying code) and Data (from storage or other sources).

Class Questions
1. What is the syntax to inherit from a class in C#?
Place a colon and then the name of the base class.
Example: class MyNewClass : MyBaseClass

2. Can you prevent your class from being inherited by another class?
Yes. The keyword “sealed” will prevent the class from being inherited.

3. Can you allow a class to be inherited, but prevent the method from being over-ridden?
Yes. Just leave the class public and make the method sealed.

4. What’s an abstract class?
A class that cannot be instantiated. An abstract class is a class that must be inherited and have the methods overridden. An abstract class is essentially a blueprint for a class without any implementation.

5. When do you absolutely have to declare a class as abstract?
1. When the class itself is inherited from an abstract class, but not all base abstract methods have been overridden.
2. When at least one of the methods in the class is abstract.

6. What is an interface class?
Interfaces, like classes, define a set of properties, methods, and events. But unlike classes, interfaces do not provide implementation. They are implemented by classes, and defined as separate entities from classes.

7. Why can’t you specify the accessibility modifier for methods inside the interface?
They all must be public, and are therefore public by default.

8. Can you inherit multiple interfaces?
Yes. .NET does support multiple interfaces.

9. 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.
To Do: Investigate

10. What’s the difference between an interface and abstract class?
In an interface class, all methods are abstract - there is no implementation. In an abstract class some methods can be concrete. In an interface class, no accessibility modifiers are allowed. An abstract class may have accessibility modifiers.

11. What is the difference between a Struct and a Class?
Structs are value-type variables and are thus saved on the stack, additional overhead but faster retrieval. Another difference is that structs cannot inherit.

Method and Property Questions
1. What’s the implicit name of the parameter that gets passed into the set method/property of a class?
Value. The data type of the value parameter is defined by whatever data type the property is declared as.

2. What does the keyword “virtual” declare for a method or property?
The method or property can be overridden.

3. How is method overriding different from method overloading?
When overriding a method, you change the behavior of the method for the derived class. Overloading a method simply involves having another method with the same name within the class.

4. Can you declare an override method to be static if the original method is not static?
No. The signature of the virtual method must remain the same. (Note: Only the keyword virtual is changed to keyword override)

5. What are the different ways a method can be overloaded?
Different parameter data types, different number of parameters, different order of parameters.

6. If a base class has a number of overloaded constructors, and an inheriting class has a number of overloaded constructors; can you enforce a call from an inherited constructor to a specific base constructor?
Yes, just place a colon, and then keyword base (parameter list to invoke the appropriate constructor) in the overloaded constructor definition inside the inherited class.

Events and Delegates
1. What’s a delegate?
A delegate object encapsulates a reference to a method.

2. What’s a multicast delegate?
A delegate that has multiple handlers assigned to it. Each assigned handler (method) is called.

XML Documentation Questions
1. Is XML case-sensitive?
Yes.

2. What’s the difference between // comments, /* */ comments and /// comments?
Single-line comments, multi-line comments, and XML documentation comments.

3. How do you generate documentation from the C# file commented properly with a command-line compiler?
Compile it with the /doc switch.

Debugging and Testing Questions
1. 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.

2. What does assert() method do?
In debug compilation, assert takes in a Boolean condition as a parameter, and shows the error dialog if the condition is false. The program proceeds without any interruption if the condition is true.

3. What’s the difference between the Debug class and Trace class?
Documentation looks the same. Use Debug class for debug builds, use Trace class for both debug and release builds.

4. Why are there five tracing levels in System.Diagnostics.TraceSwitcher?
The tracing dumps can be quite verbose. For applications that are constantly running you run the risk of overloading the machine and the hard drive. Five levels range from None to Verbose, allowing you to fine-tune the tracing activities.

5. Where is the output of TextWriterTraceListener redirected?
To the Console or a text file depending on the parameter passed to the constructor.

6. How do you debug an ASP.NET Web application?
Attach the aspnet_wp.exe process to the DbgClr debugger.

7. What are three test cases you should go through in unit testing?
1. Positive test cases (correct data, correct output).
2. Negative test cases (broken or missing data, proper handling).
3. Exception test cases (exceptions are thrown and caught properly).

8. Can you change the value of a variable while debugging a C# application?
Yes. If you are debugging via Visual Studio.NET, just go to Immediate window.

ADO.NET and Database Questions
1. What is the role of the DataReader class in ADO.NET connections?
It returns a read-only, forward-only rowset from the data source. A DataReader provides fast access when a forward-only sequential read is needed.

2. What are advantages and disadvantages of Microsoft-provided data provider classes in ADO.NET?
SQLServer.NET data provider is high-speed and robust, but requires SQL Server license purchased from Microsoft. OLE-DB.NET is universal for accessing other sources, like Oracle, DB2, Microsoft Access and Informix. OLE-DB.NET is a .NET layer on top of the OLE layer, so it’s not as fastest and efficient as SqlServer.NET.

3. What is the wildcard character in SQL?
Let’s say you want to query database with LIKE for all employees whose name starts with La. The wildcard character is %, the proper query with LIKE would involve ‘La%’.

4. Explain ACID rule of thumb for transactions.
A transaction must be:
1. Atomic - it is one unit of work and does not dependent on previous and following transactions.
2. Consistent - data is either committed or roll back, no “in-between” case where something has been updated and something hasn’t.
3. Isolated - no transaction sees the intermediate results of the current transaction).
4. Durable - the values persist if the data had been committed even if the system crashes right after.

5. What connections does Microsoft SQL Server support?
Windows Authentication (via Active Directory) and SQL Server authentication (via Microsoft SQL Server username and password).

6. Between Windows Authentication and SQL Server Authentication, which one is trusted and which one is untrusted?
Windows Authentication is trusted because the username and password are checked with the Active Directory, the SQL Server authentication is untrusted, since SQL Server is the only verifier participating in the transaction.

7. What does the Initial Catalog parameter define in the connection string?
The database name to connect to.

8. What does the Dispose method do with the connection object?
Deletes it from the memory.
To Do: answer better. The current answer is not entirely correct.

9. What is a pre-requisite for connection pooling?
Multiple processes must agree that they will share the same connection, where every parameter is the same, including the security settings. The connection string must be identical.

Assembly Questions
1. How is the DLL Hell problem solved in .NET?
Assembly versioning allows the application to specify not only the library it needs to run (which was available under Win32), but also the version of the assembly.

2. What are the ways to deploy an assembly?
An MSI installer, a CAB archive, and XCOPY command.

3. What is a satellite assembly?
When you write a multilingual or multi-cultural application in .NET, and want to distribute the core application separately from the localized modules, the localized assemblies that modify the core application are called satellite assemblies.

4. What namespaces are necessary to create a localized application?
System.Globalization and System.Resources.

5. What is the smallest unit of execution in .NET?
an Assembly.

6. When should you call the garbage collector in .NET?
As a good rule, you should not call the garbage collector. However, you could call the garbage collector when you are done using a large object (or set of objects) to force the garbage collector to dispose of those very large objects from memory. However, this is usually not a good practice.

7. How do you convert a value-type to a reference-type?
Use Boxing.

8. What happens in memory when you Box and Unbox a value-type?
Boxing converts a value-type to a reference-type, thus storing the object on the heap. Unboxing converts a reference-type to a value-type, thus storing the value on the stack.

c# FAQs-3



1. What’s the implicit name of the parameter that gets passed into the class’ set method?
Value, and its datatype depends on whatever variable we’re changing.

2. How do you inherit from a class in C#?
Place a colon and then the name of the base class. Notice that it’s double colon in C++.

3. Does C# support multiple inheritance?
No, use interfaces instead.

4. When you inherit a protected class-level variable, who is it available to?
Classes in the same namespace.

5. Are private class-level variables inherited?
Yes, but they are not accessible, so looking at it you can honestly say that they are not inherited. But they are.

6. Describe the accessibility modifier protected internal.
It’s available to derived classes and classes within the same Assembly (and naturally from the base class it’s declared in).

7. C# provides a default constructor for me. I write a constructor that takes a string as a parameter, but want to keep the no parameter one. How many constructors should I write? Two. Once you write at least one constructor, C# cancels the freebie constructor, and now you have to write one yourself, even if there’s no implementation in it.

8. What’s the top .NET class that everything is derived from?
System.Object.

9. How’s method overriding different from overloading?
When overriding, you change the method behavior for a derived class. Overloading simply involves having a method with the same name within the class.

10. What does the keyword virtual mean in the method definition?
The method can be over-ridden.

11. Can you declare the override method static while the original method is non-static?
No, you can’t, the signature of the virtual method must remain the same, only the keyword virtual is changed to keyword override.

12. Can you override private virtual methods?
No, moreover, you cannot access private methods in inherited classes, have to be protected in the base class to allow any sort of access.

13. Can you prevent your class from being inherited and becoming a base class for some other classes?
Yes, that’s what keyword sealed in the class definition is for. The developer trying to derive from your class will get a message: cannot inherit from Sealed class WhateverBaseClassName. It’s the same concept as final class in Java.

14. Can you allow class to be inherited, but prevent the method from being over-ridden?
Yes, just leave the class public and make the method sealed.

15. What’s an abstract class?
A class that cannot be instantiated. A concept in C++ known as pure virtual method. A class that must be inherited and have the methods over-ridden. Essentially, it’s a blueprint for a class without any implementation.

16. When do you absolutely have to declare a class as abstract (as opposed to free-willed educated choice or decision based on UML diagram)?
When at least one of the methods in the class is abstract. When the class itself is inherited from an abstract class, but not all base abstract methods have been over-ridden.

17. What’s an interface class?
It’s an abstract class with public abstract methods all of which must be implemented in the inherited classes.

18. Why can’t you specify the accessibility modifier for methods inside the interface?
They all must be public. Therefore, to prevent you from getting the false impression that you have any freedom of choice, you are not allowed to specify any accessibility, it’s public by default.

19. Can you inherit multiple interfaces?
Yes, why not.

20. And if 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.

21. What’s the difference between an interface and abstract class?
In the interface all methods must be abstract; in the abstract class some methods can be concrete. In the interface no accessibility modifiers are allowed, which is ok in abstract classes.

22. How can you overload a method?
Different parameter data types, different number of parameters, different order of parameters.

23. If a base class has a bunch of overloaded constructors, and an inherited class has another bunch of overloaded constructors, can you enforce a call from an inherited constructor to an arbitrary base constructor?
Yes, just place a colon, and then keyword base (parameter list to invoke the appropriate constructor) in the overloaded constructor definition inside the inherited class.

24. What’s the difference between System.String and System.StringBuilder classes? System.String is immutable; System.StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed.

25. What’s the advantage of using System.Text.StringBuilder over System.String?
StringBuilder is more efficient in the cases, where a lot of manipulation is done to the text. Strings are immutable, so each time it’s being operated on, a new instance is created.

26. Can you store multiple data types in System.Array?
No.

27. What’s the difference between the System.Array.CopyTo() and System.Array.Clone()?
The first one performs a deep copy of the array, the second one is shallow.

28. How can you sort the elements of the array in descending order?
By calling Sort() and then Reverse() methods.

29. What’s the .NET datatype that allows the retrieval of data by a unique key?
HashTable.

30. What’s class SortedList underneath?
A sorted HashTable.

31. Will finally block get executed if the exception had not occurred?
Yes.

32. What’s the C# equivalent of C++ catch (…), which was a catch-all statement for any possible
exception?
A catch block that catches the exception of type System.Exception. You can also omit the parameter data type in this case and just write catch {}.

33. Can multiple catch blocks be executed?
No, once the proper catch code fires off, the control is transferred to the finally block (if there are any), and then whatever follows the finally block.

34. Why is it a bad idea to throw your own exceptions?
Well, if at that point you know that an error has occurred, then why not write the proper code to handle that error instead of passing a new Exception object to the catch block? Throwing your own exceptions signifies some design flaws in the project.

35. What’s a delegate?
A delegate object encapsulates a reference to a method. In C++ they were referred to as function pointers.

36. What’s a multicast delegate?
It’s a delegate that points to and eventually fires off several methods.

37. How’s the DLL Hell problem solved in .NET?
Assembly versioning allows the application to specify not only the library it needs to run (which was available under Win32), but also the version of the assembly.

38. What are the ways to deploy an assembly?
An MSI installer, a CAB archive, and XCOPY command.

39. What’s a satellite assembly?
When you write a multilingual or multi-cultural application in .NET, and want to distribute the core application separately from the localized modules, the localized assemblies that modify the core application are called satellite assemblies.

40. What namespaces are necessary to create a localized application?
System.Globalization, System.Resources.

41. What’s the difference between // comments, /* */ comments and /// comments?
Single-line, multi-line and XML documentation comments.

42. How do you generate documentation from the C# file commented properly with a command-line compiler?
Compile it with a /doc switch.

43. What’s the difference between and XML documentation tag?
Single line code example and multiple-line code example.

44. Is XML case-sensitive?
Yes, so and are different elements.

45. What debugging tools come with the .NET SDK?
CorDBG – command-line debugger, and DbgCLR – graphic debugger. Visual Studio .NET uses the DbgCLR. To use CorDbg, you must compile the original C# file using the /debug switch.

46. What does the This window show in the debugger?
It points to the object that’s pointed to by this reference. Object’s instance data is shown.

47. What does assert() do?
In debug compilation, assert takes in a Boolean condition as a parameter, and shows the error dialog if the condition is false. The program proceeds without any interruption if the condition is true.

48. What’s the difference between the Debug class and Trace class?
Documentation looks the same. Use Debug class for debug builds, use Trace class for both debug and release builds.

49. Why are there five tracing levels in System.Diagnostics.TraceSwitcher?
The tracing dumps can be quite verbose and for some applications that are constantly running you run the risk of overloading the machine and the hard drive there. Five levels range from None to Verbose, allowing to fine-tune the tracing activities.

50. Where is the output of TextWriterTraceListener redirected?
To the Console or a text file depending on the parameter passed to the constructor.

51. How do you debug an ASP.NET Web application?
Attach the aspnet_wp.exe process to the DbgClr debugger.

52. What are three test cases you should go through in unit testing?
Positive test cases (correct data, correct output), negative test cases (broken or missing data, proper handling), exception test cases (exceptions are thrown and caught properly).

53. Can you change the value of a variable while debugging a C# application?
Yes, if you are debugging via Visual Studio.NET, just go to Immediate window.

54. Explain the three services model (three-tier application).
Presentation (UI), business (logic and underlying code) and data (from storage or other sources).

55. What are advantages and disadvantages of Microsoft-provided data provider classes in ADO.NET?
SQLServer.NET data provider is high-speed and robust, but requires SQL Server license purchased from Microsoft. OLE-DB.NET is universal for accessing other sources, like Oracle, DB2, Microsoft Access and Informix, but it’s a .NET layer on top of OLE layer, so not the fastest thing in the world. ODBC.NET is a deprecated layer provided for backward compatibility to ODBC engines.

56. What’s the role of the DataReader class in ADO.NET connections?
It returns a read-only dataset from the data source when the command is executed.

57. What is the wildcard character in SQL?
Let’s say you want to query database with LIKE for all employees whose name starts with La. The wildcard character is %, the proper query with LIKE would involve ‘La%’.

58. Explain ACID rule of thumb for transactions.
Transaction must be Atomic (it is one unit of work and does not dependent on previous and following transactions), Consistent (data is either committed or roll back, no “in-between” case where something has been updated and something hasn’t), Isolated (no transaction sees the intermediate results of the current transaction), Durable (the values persist if the data had been committed even if the system crashes right after).

59. What connections does Microsoft SQL Server support?
Windows Authentication (via Active Directory) and SQL Server authentication (via Microsoft SQL Server username and passwords).

60. Which one is trusted and which one is untrusted?
Windows Authentication is trusted because the username and password are checked with the Active Directory, the SQL Server authentication is untrusted, since SQL Server is the only verifier participating in the transaction.

61. Why would you use untrusted verificaion?
Web Services might use it, as well as non-Windows applications.

62. What does the parameter Initial Catalog define inside Connection String?
The database name to connect to.

63. What’s the data provider name to connect to Access database?
Microsoft.Access.

64. What does Dispose method do with the connection object?
Deletes it from the memory.

65. What is a pre-requisite for connection pooling?
Multiple processes must agree that they will share the same connection, where every parameter is the same, including the security settings.

C# FAQs-2

1. Name 10 C# keywords.
abstract, event, new, struct, explicit, null, base, extern, object, this
2. What is public accessibility?
There are no access restrictions.
3. What is protected accessibility?
Access is restricted to types derived from the containing class.
4. What is internal accessibility?
A member marked internal is only accessible from files within the same assembly.
5. What is protected internal accessibility?
Access is restricted to types derived from the containing class or from files within the same assembly.
6. What is private accessibility?
Access is restricted to within the containing class.
7. What is the default accessibility for a class?
internal for a top level class, private for a nested one.
8. What is the default accessibility for members of an interface?
public
9. What is the default accessibility for members of a struct?
private
10. Can the members of an interface be private?
No.
11. Methods must declare a return type, what is the keyword used when nothing is returned from the method?
void
12. Class methods to should be marked with what keyword?
static
13. Write some code using interfaces, virtual methods, and an abstract class.
using System;

public interface Iexample1
{
int MyMethod1();
}

public interface Iexample2
{
int MyMethod2();
}

public abstract class ABSExample : Iexample1, Iexample2
{
public ABSExample()
{
System.Console.WriteLine("ABSExample constructor");
}

public int MyMethod1()
{
return 1;
}

public int MyMethod2()
{
return 2;
}

public abstract void MyABSMethod();
}

public class VIRTExample : ABSExample
{
public VIRTExample()
{
System.Console.WriteLine("VIRTExample constructor");
}

public override void MyABSMethod()
{
System.Console.WriteLine("Abstract method made concrete");
}

public virtual void VIRTMethod1()
{
System.Console.WriteLine("VIRTMethod1 has NOT been overridden");
}

public virtual void VIRTMethod2()
{
System.Console.WriteLine("VIRTMethod2 has NOT been overridden");
}
}

public class FinalClass : VIRTExample
{
public override void VIRTMethod2()
{
System.Console.WriteLine("VIRTMethod2 has been overridden");
}
}
14. A class can have many mains, how does this work?
Only one of them is run, that is the one marked (public) static, e.g:
public static void Main(string[] args)
{
//
// TODO: Add code to start application here
//
}

private void Main(string[] args, int i)
{
}
15. Does an object need to be made to run main?
No
16. Write a hello world console application.
using System;

namespace Console1
{
class Class1
{
[STAThread] // No longer needed
static void Main(string[] args)
{
Console.WriteLine("Hello world");
}
}
}
17. What are the two return types for main?
void and int
18. What is a reference parameter?
Reference parameters reference the original object whereas value parameters make a local copy and do not affect the original. Some example code is shown:
using System;

namespace Console1
{
class Class1
{
static void Main(string[] args)
{
TestRef tr1 = new TestRef();
TestRef tr2 = new TestRef();

tr1.TestValue = "Original value";
tr2.TestValue = "Original value";
int tv1 = 1;
int tv2 = 1;

TestRefVal(ref tv1, tv2, ref tr1, tr2);

Console.WriteLine(tv1);
Console.WriteLine(tv2);
Console.WriteLine(tr1.TestValue);
Console.WriteLine(tr2.TestValue);

Console.ReadLine();
}

static public void TestRefVal(ref int tv1Parm,
int tv2Parm,
ref TestRef tr1Parm,
TestRef tr2Parm)
{
tv1Parm = 2;
tv2Parm = 2;
tr1Parm.TestValue = "New value";
tr2Parm.TestValue = "New value";
}
}
}

class TestRef
{
public string TestValue;
}

The output for this is:

2
1
New value
New value
19. What is an out parameter?
An out parameter allows an instance of a parameter object to be made inside a method. Reference parameters must be initialised but out gives a reference to an uninstanciated object.
20. Write code to show how a method can accept a varying number of parameters.
using System;

namespace Console1
{
class Class1
{
static void Main(string[] args)
{
ParamsMethod(1,"example");
ParamsMethod(1,2,3,4);

Console.ReadLine();
}

static void ParamsMethod(params object[] list)
{
foreach (object o in list)
{
Console.WriteLine(o.ToString());
}
}
}
}
21. What is an overloaded method?
An overloaded method has multiple signatures that are different.
22. What is recursion?
Recursion is when a method calls itself.
23. What is a constructor?
A constructor performs initialisation for an object (including the struct type) or class.
24. If I have a constructor with a parameter, do I need to explicitly create a default constructor?
Yes
25. What is a destructor?
A C# destuctor is not like a C++ destructor. It is actually an override for Finalize(). This is called when the garbage collector discovers that the object is unreachable. Finalize() is called before any memory is reclaimed.
26. Can you use access modifiers with destructors?
No
27. What is a delegate?
A delegate in C# is like a function pointer in C or C++. A delegate is a variable that calls a method indirectly, without knowing its name. Delegates can point to static or/and member functions. It is also possible to use a multicast delegate to point to multiple functions.
28. Write some code to use a delegate.
Member function with a parameter
using System;

namespace Console1
{
class Class1
{
delegate void myDelegate(int parameter1);

static void Main(string[] args)
{
MyClass myInstance = new MyClass();

myDelegate d = new myDelegate(myInstance.AMethod);

d(1); // <--- Calling function without knowing its name. Test2(d); Console.ReadLine(); } static void Test2(myDelegate d) { d(2); // <--- Calling function without knowing its name. } } class MyClass { public void AMethod(int param1) { Console.WriteLine(param1); } } } Multicast delegate calling static and member functions using System; namespace Console1 { class Class1 { delegate void myDelegate(int parameter1); static void AStaticMethod(int param1) { Console.WriteLine(param1); } static void Main(string[] args) { MyClass myInstance = new MyClass(); myDelegate d = null; d += new myDelegate(myInstance.AMethod); d += new myDelegate(AStaticMethod); d(1); //both functions will be run. Console.ReadLine(); } } class MyClass { public void AMethod(int param1) { Console.WriteLine(param1); } } } 29. What is a delegate useful for? The main reason we use delegates is for use in event driven programming. 30. What is an event? See 32 31. Are events synchronous of asynchronous? Asynchronous 32. Events use a publisher/subscriber model. What is that? Objects publish events to which other applications subscribe. When the publisher raises an event all subscribers to that event are notified. 33. Can a subscriber subscribe to more than one publisher? Yes, also - here's some code for a publisher with multiple subscribers. using System; namespace Console1 { class Class1 { delegate void myDelegate(int parameter1); static event myDelegate myEvent; static void AStaticMethod(int param1) { Console.WriteLine(param1); } static void Main(string[] args) { MyClass myInstance = new MyClass(); myEvent += new myDelegate(myInstance.AMethod); myEvent += new myDelegate(AStaticMethod); myEvent(1); //both functions will be run. Console.ReadLine(); } } class MyClass { public void AMethod(int param1) { Console.WriteLine(param1); } } } Another example: using System; using System.Threading; namespace EventExample { public class Clock { public delegate void TwoSecondsPassedHandler(object clockInstance, TimeEventArgs time); //The clock publishes an event that others subscribe to public event TwoSecondsPassedHandler TwoSecondsPassed; public void Start() { while(true) { Thread.Sleep(2000); //Raise event TwoSecondsPassed(this, new TimeEventArgs(1)); } } } public class TimeEventArgs : EventArgs { public TimeEventArgs(int second) { seconds += second; instanceSeconds = seconds; } private static int seconds; public int instanceSeconds; } public class MainClass { static void Main(string[] args) { Clock cl = new Clock(); // add some subscribers cl.TwoSecondsPassed += new Clock.TwoSecondsPassedHandler(Subscriber1); cl.TwoSecondsPassed += new Clock.TwoSecondsPassedHandler(Subscriber2); cl.Start(); Console.ReadLine(); } public static void Subscriber1(object clockInstance, TimeEventArgs time) { Console.WriteLine("Subscriber1:" + time.instanceSeconds); } public static void Subscriber2(object clockInstance, TimeEventArgs time) { Console.WriteLine("Subscriber2:" + time.instanceSeconds); } } } 34. What is a value type and a reference type? A reference type is known by a reference to a memory location on the heap. A value type is directly stored in a memory location on the stack. A reference type is essentially a pointer, dereferencing the pointer takes more time than directly accessing the direct memory location of a value type. 35. Name 5 built in types. Bool, char, int, byte, double 36. string is an alias for what? System.String 37. Is string Unicode, ASCII, or something else? Unicode 38. Strings are immutable, what does this mean? Any changes to that string are in fact copies. 39. Name a few string properties. trim, tolower, toupper, concat, copy, insert, equals, compare. 40. What is boxing and unboxing? Converting a value type (stack->heap) to a reference type (heap->stack), and vise-versa.
41. Write some code to box and unbox a value type.
// Boxing
int i = 4;
object o = i;
// Unboxing
i = (int) o;
42. What is a heap and a stack?
There are 2 kinds of heap – 1: a chunk of memory where data is stored and 2: a tree based data structure. When we talk about the heap and the stack we mean the first kind of heap. The stack is a LIFO data structure that stores variables and flow control information. Typically each thread will have its own stack.
43. What is a pointer?
A pointer is a reference to a memory address.
44. What does new do in terms of objects?
Initializes an object.
45. How do you dereference an object?
Set it equal to null.
46. In terms of references, how do == and != (not overridden) work?
They check to see if the references both point to the same object.
47. What is a struct?
Unlike in C++ a struct is not a class – it is a value type with certain restrictions. It is usually best to use a struct to represent simple entities with a few variables. Like a Point for example which contains variables x and y.
48. Describe 5 numeric value types ranges.
sbyte -128 to 127, byte 0 – 255, short -32,768 to 32,767, int -2,147,483,648 to 2,147,483,647, ulong 0 to 18,446,744,073,709,551,615
49. What is the default value for a bool?
false
50. Write code for an enumeration.
public enum animals {Dog=1,Cat,Bear};
51. Write code for a case statement.
switch (n)
{
case 1:
x=1;
break;
case 2:
x=2;
break;
default:
goto case 1;
}
52. Is a struct stored on the heap or stack?
Stack
53. Can a struct have methods?
Yes
54. What is checked { } and unchecked { }?
By default C# does not check for overflow (unless using constants), we can use checked to raise an exception. E.g.:
static short x = 32767; // Max short value
static short y = 32767;

// Using a checked expression
public static int myMethodCh()
{
int z = 0;

try
{
z = checked((short)(x + y));
//z = (short)(x + y);
}
catch (System.OverflowException e)
{
System.Console.WriteLine(e.ToString());
}
return z; // Throws the exception OverflowException
}

This code will raise an exception, if we remove unchecked as in:

//z = checked((short)(x + y));
z = (short)(x + y);

Then the cast will raise no overflow exception and z will be assigned –2. unchecked can be used in the opposite way, to say avoid compile time errors with constanst overflow. E.g. the following will cause a compiler error:

const short x = 32767; // Max short value
const short y = 32767;

public static int myMethodUnch()
{
int z = (short)(x + y);
return z; // Returns -2
}

The following will not:

const short x = 32767; // Max short value
const short y = 32767;

public static int myMethodUnch()
{
int z = unchecked((short)(x + y));
return z; // Returns -2
}
55. Can C# have global overflow checking?
Yes
56. What is explicit vs. implicit conversion?
When converting from a smaller numeric type into a larger one the cast is implicit. An example of when an explicit cast is needed is when a value may be truncated.
57. Give examples of both of the above.
// Implicit
short shrt = 400;
int intgr = shrt;

// Explicit
shrt = (short) intgr;
58. Can assignment operators be overloaded directly?
No
59. What do operators is and as do?
as acts is like a cast but returns a null on conversion failure. Is comares an object to a type and returns a boolean.
60. What is the difference between the new operator and modifier?
The new operator creates an instance of a class whereas the new modifier is used to declare a method with the same name as a method in one of the parent classes.
61. Explain sizeof and typeof.
typeof obtains the System.Type object for a type and sizeof obtains the size of a type.
62. What doe the stackalloc operator do?
Allocate a block of memory on the stack (used in unsafe mode).
63. Contrast ++count vs. count++.
Some operators have temporal properties depending on their placement. E.g.
double x;
x = 2;
Console.Write(++x);
x = 2;
Console.Write(x++);
Console.Write(x);
Returns
323
64. What are the names of the three types of operators?
Unary, binary, and conversion.
65. An operator declaration must include a public and static modifier, can it have other modifiers?
No
66. Can operator parameters be reference parameters?
No
67. Describe an operator from each of these categories:
Arithmetic: +Logical (boolean and bitwise): &String concatenation: +Increment, decrement: ++Shift: >>Relational: ==Assignment: =Member access: .Indexing: []Cast: ()Conditional: ?:Delegate concatenation and removal: +Object creation: newType information: asOverflow exception control: checkedIndirection and Address: *
68. What does operator order of precedence mean?
Certain operators are evaluated before others. Brackets help to avoid confusion.
69. What is special about the declaration of relational operators?
Relational operators must be declared in pairs.
70. Write some code to overload an operator.
class TempleCompare
{

public int templeCompareID;
public int templeValue;

public static bool operator == (TempleCompare x, TempleCompare y) { return (x.templeValue == y.templeValue); }
public static bool operator != (TempleCompare x, TempleCompare y) { return !(x == y); }

public override bool Equals(object o)
{
// check types match
if (o == null GetType()!= o.GetType()) return false;
TempleCompare t = (templeCompare) o;
return (this.templeCompareID == t.templeCompareID) && (this.templeValue == t.templeValue);
}

public override int GetHashCode() { return templeCompareID; }
}
71. What operators cannot be overloaded?
=, ., ?:, ->, new, is, sizeof, typeof
72. What is an exception?
A runtime error.
73. Can C# have multiple catch blocks?
Yes
74. Can break exit a finally block?
No
75. Can Continue exit a finally block?
No
76. Write some try…catch…finally code.
// try-catch-finally
using System;
public class TCFClass
{
public static void Main ()
{
try
{
throw new NullReferenceException();
}

catch(NullReferenceException e)
{
Console.WriteLine("{0} exception 1.", e);
}

catch
{
Console.WriteLine("exception 2.");
}

finally
{
Console.WriteLine("finally block.");
}
}
}
77. What are expression and declaration statements?
· Expression – produces a value e.g. blah = 0
· Declaration – e.g. int blah;
78. A block contains a statement list {s1;s2;} what is an empty statement list?
{;}
79. Write some if… else if… code.
int n=4;

if (n==1)
Console.WriteLine("n=1");
else if (n==2)
Console.WriteLine("n=2");
else if (n==3)
Console.WriteLine("n=3");
else
Console.WriteLine("n>3");
80. What is a dangling else?
if (n>0)
if (n2>0)
Console.Write("Dangling Else")
else
81. Is switch case sensitive?
Yes
82. Write some code for a for loop
for (int i = 1; i <= 5; i++) Console.WriteLine(i); 83. Can you increment multiple variables in a for loop control? Yes – e.g. for (int i = 1; j = 2;i <= 5 ;i++ ;j=j+2) 84. Write some code for a while loop. int n = 1; while (n < y =" 0;" x =" y++;" x =" 0," y =" 0;" arr =" new" 2 ="=" contents =" contents;" location =" -1;" i =" i;" location =" -1;" myarray =" {" items =" new" c1 =" 5;" b =" {{0," myarray =" new" list =" new" m =" new" mydata =" {" a =" value;" allowmultiple="true)]" name =" name;" version =" 1.0;" tc1 =" new" tc2 =" new" ot1 =" new" ot2 =" new" lockvalue = "dummy" threadnumber =" threadNumber;">
///
///
///
///
///
///
///
///

///
///
///
///
///
///
///

158. What is unsafe code?
Unsafe code bypasses type safety and memory management.
159. What does the fixed statement do?
Prevents relocation of a variable by GC.
160. How would you read and write using the console?
Console.Write, Console.WriteLine, Console.Readline
161. Give examples of hex, currency, and fixed point console formatting.
Console.Write("{0:X}", 250); à FA
Console.Write("{0:C}", 2.5); à $2.50
Console.Write("{0:F2}", 25); à 25.00
162. Given part of a stack trace: aspnet.debugging.BadForm.Page_Load(Object sender, EventArgs e) +34. What does the +34 mean?
It is an actual offset (at the assembly language level) – not an offset into the IL instructions.
163. Are value types are slower to pass as method parameters?
Yes
164. How can you implement a mutable string?
System.Text.StringBuilder
165. What is a thread pool?
A thread pool is a means by which to control a number of threads simultaneously. Thread pools give us thread reuse, rather than creating a new thread every time.
166. Describe the CLR security model.
From
http://msdn.microsoft.com/msdnmag/issues/02/09/SecurityinNET/default.aspx
“Unlike the old principal-based security, the CLR enforces security policy based on where code is coming from rather than who the user is. This model, called code access security, makes sense in today's environment because so much code is installed over the Internet and even a trusted user doesn't know when that code is safe.”
167. What’s the difference between camel and pascal casing?
PascalCasing, camelCasing
168. What does marshalling mean?
From
http://www.dictionary.net/marshalling
“The process of packing one or more items of data into a message buffer, prior to transmitting that message buffer over a communication channel. The packing process not only collects together values which may be stored in non-consecutive memory locations but also converts data of different types into a standard representation agreed with the recipient of the message.”
169. What is inlining?
From (Google web defintions)
“In-line expansion or inlining for short is a compiler optimization which "expands" a function call site into the actual implementation of the function which is called, rather than each call transferring control to a common piece of code. This reduces overhead associated with the function call, which is especially important for small and frequently called functions, and it helps call-site-specific compiler optimizations, especially constant propagation.”
170. List the differences in C# 2.0.
· Generics
· Iterators
· Partial class definitions
· Nullable Types
· Anonymous methods
· :: operator
· Static classes static class members
· Extern keyword
· Accessor accessibility
· Covariance and Contravariance
· Fixed size buffers
· Fixed assemblies
· #pragma warning
171. What are design patterns?
From
http://www.dofactory.com/Patterns/Patterns.aspx
“Design patterns are recurring solutions to software design problems you find again and again in real-world application development.”
172. Describe some common design patterns.
From
http://www.dofactory.com/Patterns/Patterns.aspx
Creational Patterns
Abstract Factory Creates an instance of several families of classes
Builder Separates object construction from its representation
Factory Method Creates an instance of several derived classes
Prototype A fully initialized instance to be copied or cloned
Singleton A class of which only a single instance can exist
Structural Patterns
Adapter Match interfaces of different classes
Bridge Separates an object’s interface from its implementation
Composite A tree structure of simple and composite objects
Decorator Add responsibilities to objects dynamically
Façade A single class that represents an entire subsystem
Flyweight A fine-grained instance used for efficient sharing
Proxy An object representing another object
Behavioral Patterns
Chain of Resp. A way of passing a request between a chain of objects
Command Encapsulate a command request as an object
Interpreter A way to include language elements in a program
Iterator Sequentially access the elements of a collection
Mediator Defines simplified communication between classes
Memento Capture and restore an object's internal state
Observer A way of notifying change to a number of classes
State Alter an object's behavior when its state changes
Strategy Encapsulates an algorithm inside a class
Template Method Defer the exact steps of an algorithm to a subclass
Visitor Defines a new operation to a class without change
173. What are the different diagrams in UML? What are they used for?
From

http://www.developer.com/design/article.php/1553851


“Use case diagram: The use case diagram is used to identify the primary elements and processes that form the system. The primary elements are termed as "actors" and the processes are called "use cases." The use case diagram shows which actors interact with each use case.
Class diagram: The class diagram is used to refine the use case diagram and define a detailed design of the system. The class diagram classifies the actors defined in the use case diagram into a set of interrelated classes. The relationship or association between the classes can be either an "is-a" or "has-a" relationship. Each class in the class diagram may be capable of providing certain functionalities. These functionalities provided by the class are termed "methods" of the class. Apart from this, each class may have certain "attributes" that uniquely identify the class.
Object diagram: The object diagram is a special kind of class diagram. An object is an instance of a class. This essentially means that an object represents the state of a class at a given point of time while the system is running. The object diagram captures the state of different classes in the system and their relationships or associations at a given point of time.
State diagram: A state diagram, as the name suggests, represents the different states that objects in the system undergo during their life cycle. Objects in the system change states in response to events. In addition to this, a state diagram also captures the transition of the object's state from an initial state to a final state in response to events affecting the system.
Activity diagram: The process flows in the system are captured in the activity diagram. Similar to a state diagram, an activity diagram also consists of activities, actions, transitions, initial and final states, and guard conditions.
Sequence diagram: A sequence diagram represents the interaction between different objects in the system. The important aspect of a sequence diagram is that it is time-ordered. This means that the exact sequence of the interactions between the objects is represented step by step. Different objects in the sequence diagram interact with each other by passing "messages".
Collaboration diagram: A collaboration diagram groups together the interactions between different objects. The interactions are listed as numbered interactions that help to trace the sequence of the interactions. The collaboration diagram helps to identify all the possible interactions that each object has with other objects.
Component diagram: The component diagram represents the high-level parts that make up the system. This diagram depicts, at a high level, what components form part of the system and how they are interrelated. A component diagram depicts the components culled after the system has undergone the development or construction phase.
Deployment diagram: The deployment diagram captures the configuration of the runtime elements of the application. This diagram is by far most useful when a system is built and ready to be deployed.”

C# FAQs-1

1. What is MSIL?
Microsoft Intermediate Language (MSIL) is the CPU-independent instruction set generated by .NET compilers from .NET languages such as J#, C# or Visual Basic. MSIL is compiled before or during execution of the program by a Virtual Execution System (VES), which is part of the Common Language Runtime module (CLR).

2. What is the CLR and how is it different from a JVM?
The JVM can either interpret or just-in-time compile the byte code. The CLR always compiles to native code. Another is that the CLR supports unmanaged code, known as “unsafe”, where the programmer assumes the responsibility for managing memory and can do pointer arithmetic and so forth.

3. What is WinFX?
The new Windows API that will be released with the Microsoft Longhorn Operating System. This will include features for Avalon, Indigo, and WinFS as well as a number of fundamental routines.

4. What is Indigo?
The code name for the communications portion of Longhorn that is built around Web services. This communications technology focuses on providing spanning transports, security, messaging patterns, encoding, networking and hosting, and more.

5. Explain the Remoting architecture.
From http://www.kippsoftware.com/san200405.htm
· The developer first instantiates locally a proxy interface to the remote assembly. Local code calls a method of the proxy
· The .NET platform calls the corresponding method on the remote server and returns the results (see figure).
· Developers can use TCP or HTTP remoting.
· Remoting makes use of Leases and allocations to improve efficiency.

6. How would you write an asynchronous webservice?
Use a callback and call BeginSubmit yourself.

7. What is the Microsoft Enterprise Library?
A set of functions that adhere to Microsoft’s Patterns and Practices guidelines. These functions include:
Caching Application Block, Configuration Application Block, Data Access Application Block, Cryptography Application Block, Exception Handling Application Block, Logging and Instrumentation Application Block and the Security Application Block.
8. Discuss System.Collections
8 – 24 From http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemcollections.asp
The System.Collections namespace contains interfaces and classes that define various collections of objects, such as lists, queues, bit arrays, hashtables and dictionaries.
9. Discuss System.Configuration
The System.Configuration namespace provides classes and interfaces that allow you to programmatically access .NET Framework configuration settings and handle errors in configuration files (.config files).
10. Discuss System.Data
The System.Data namespace consists mostly of the classes that constitute the ADO.NET architecture.
11. Discuss System.Diagnostics
The System.Diagnostics namespace provides classes that allow you to interact with system processes, event logs, and performance counters.
12. Discuss System.DirectoryServcies
The System.DirectoryServices namespace provides easy access to Active Directory from managed code.
13. Discuss System.Drawing
The System.Drawing namespace provides access to GDI+ basic graphics functionality.
14. Discuss System.EnterpriseServices
The System.EnterpriseServices namespace provides an important infrastructure for enterprise applications. COM+ provides a services architecture for component programming models deployed in an enterprise environment. This namespace provides .NET objects with access to COM+ services making the .NET Framework objects more practical for enterprise applications.
15. Discuss System.Globalization
The System.Globalization namespace contains classes that define culture-related information, including the language, the country/region, the calendars in use, the format patterns for dates, currency, and numbers, and the sort order for strings.
16. Discuss System.IO
The System.IO namespace contains types that allow reading and writing to files and data streams, and types that provide basic file and directory support.
17. Discuss System.Net
The System.Net namespace provides a simple programming interface for many of the protocols used on networks today.
18. System.Runtime contains System.Runtime.CompilerServcies, what else?
CompilerServices, InteropServices, Remoting, Serialization.
19. Discuss System.Security
The System.Security namespace provides the underlying structure of the common language runtime security system, including base classes for permissions.
20. Discuss System.Text
The System.Text namespace contains classes representing ASCII, Unicode, UTF-7, and UTF-8 character encodings; abstract base classes for converting blocks of characters to and from blocks of bytes; and a helper class that manipulates and formats String objects without creating intermediate instances of String.
21. Discuss System.Threading
The System.Threading namespace provides classes and interfaces that enable multithreaded programming.
22. Discuss System.Web
The System.Web namespace supplies classes and interfaces that enable browser-server communication.
23. Discuss System.Windows.Forms
The System.Windows.Forms namespace contains classes for creating Windows-based applications.
24. Discuss System.XML
The System.Xml namespace provides standards-based support for processing XML.
25. Does VS.NET 2003 have a web browser (think about it)?
Yes
26. How are VB.NET and C# different?
Different syntax, no unsafe VB.NET code, VB.NET is case insensitive, etc.
27. Contrast .NET with J2EE.
Overview

J2EE is a set of non-vendor specific standards for developing “fat” and “thin” applications and services, J2EE is mainly directed at “thin” clients. These standards are the collaborative effort of more than 400 companies.
.net is a tangible set of software and services designed to run on the Windows platform. The .net software and services also allow the design and implementation of enterprise and non-enterprise applications. Equal emphasis has been given to “fat” and “thin” clients. .net was developed exclusively by Microsoft.

Virtual Machines

Both .net and J2EE use a Virtual Machine to interpret intermediate code. With J2EE this intermediate code is called “Byte Code”. With .net the code is called the “Intermediate Language”. When Java or .net code is written and compiled it compiles to intermediate code.

With J2EE the JVM (Java Virtual Machine) interprets its byte code line by line into the machine’s native language. J2EE byte code can be compiled directly to native machine code or JIT (Just In Time) compiled, but the vast majority of J2EE applications are interpreted.
The .NET virtual machine, the CLR (Common Language Runtime) uses a JIT compiler to compile blocks of IL code into native machine code at run time. Visual Studio.net can also compile directly to native code.

Programming Languages

Both platforms have the option of using multiple programming languages for an enterprise application, although this is a much easier task to achieve with the .net platform.

The J2EE standard is based on Java, so applications are mainly developed in Java. Interoperability is possible through JNI (Java Native interface) and CORBA (Common Object Request Broker Architecture). The latter is almost never done as the APIs are complicated and time consuming.
.net supports the seamless integration of over 20 languages, this is done via strong typing, common interfaces and a concept called “managed code”. On the down side, the language differences are largely semantic (VB.NET vs. C#). Also, languages like C++ require extra imports (managed extensions).

Operating Systems

Both .NET and J2EE have pretensions to having portable source code.

J2EE is by far the best for portability, the whole specification is designed as to be non-vendor specific. In practice though, Java source is often not portable without modifications.
.net has promised that the CLR and core languages like C# will eventually be portable. At present .net only runs on Windows.

J2EE versus .net at Each Tier

An enterprise application can be logically separated into 3 tiers - Presentation, Business Logic, and the Data tier.

Presentation Tier

Both .net and J2EE use a scripting language at the presentation tier for “thin” clients or “Web Applications”. They also have similar ways of generating this tier for “fat” client applications.

For “thin” client applications J2EE uses Java Servlets and a derivative of ASP (Active Server Pages) called JSP (Java Server Pages), which intermingles HTML with Java based script. Calls to Business logic components (EJB - Enterprise Java Beans) are made from these JSP pages. Coding the page to render on a number of different “thin” clients must be done manually. For “fat” clients there is the Java Swing API, with a set of standard java beans and a number of different GUIs to build applications with.

.net uses Visual Studio.net for both “thin” and “fat” clients. .net “thin” client applications use the ASP.NET scripting language. ASP.NET can be used in the traditional script based way, but Microsoft encourages the use of a “Code Behind Page”. One simply drags and drops various “Web Controls” onto an ASP.NET (.aspx) page and then uses the code behind page to adjust those controls programmatically. When an .aspx page is requested by a “thin” client the page is rendered automatically by the .net runtime which checks the type of “thin” client and adjusts each control accordingly. The result is that an .aspx page can render on any supported “thin” client without any extra work. This has a down side, that being that the look n’ feel of each page is limited by the controls offered. Microsoft’s IIS server also has legacy support for ASP, so ASP.NET and ASP can be used in conjunction with each other. For “fat” clients the process is the same except that there is a different set of controls for a “Windows Form” (as opposed to a “Web Form”).

Business Logic Tier

The two technologies are very similar on this level with each borrowing concepts from the other.


Java Beans are the basic components (defined properties, event handling and persistence). EJB are the distributed equivalents that have extra functions for application level security, distributed transactions, life cycle management and resource pooling. The java runtime handles the life cycle of each component, deciding when to destroy a component (garbage collection) and what memory it can access (sandbox security).

.net uses an enriched version of COM+ (assemblies) which gives its components all of the above functions with the addition of newer concepts like extensible meta-data for each assembly. Like J2EE the “registration” of components is much easier with a new deployment model and .net projects also support traditional COM and COM+ components. Perhaps the biggest difference is the ability to go into “unmanaged mode” which allows the application to access areas of memory normally inaccessible via the CLR Sandbox.

Data Tier

For relational database access J2EE uses JDBC (Java Database Connection) – which is based on Microsoft’s ODBC (Open Database Connectivity). At a higher level it is conceptually the same as ADO (ActiveX Data Objects - which sits on top of ODBC) with connections, statements and Result sets. JDBC does perform better than ADO. For Naming and Directory Services J2EE uses JNDI (Java Naming and Directory Interface) and JDBC does not support hierarchical Database access.

.net uses ADO.NET , it has all the ADO functionality and more. All data transmission from source to component is now done via XML (eXtensible Markup Language). This means that ADO.NET can use ANYTHING that emits XML data in the ADO.NET schema as a data source. ADO.NET supports hierarchical data access, and naming and directory services are accessed via ADSI (Active Directory Services Interface).

XML, Web Services, and Remoting

Web services and remoting are web and TCP/IP based remotely callable functions that sit on top of a predetermined protocol.

J2EE’s web services run with a host of different protocols. They run with HTTP, RMI/JRMP (Remote Method Invocation / Java Remote Method Protocol) or IIOP (Internet InterORB Protocol).
.net web services run exclusively on HTTP with a SOAP (Simple Object Access Protocol) wrapper. All data interchange is done with XML. Web services in .net are all standardised with XML interfaces. Remoting uses either SOAP or TCP/IP directly. The entire .net framework is very XML centric.

Performance

In an enterprise environment .net outperforms J2EE. Benchmarks show that it is more scalable, efficient, faster to run and develop, easier to use and cheaper - sometimes by a factor of five. .net is designed to work just as well in a non-enterprise environment (pointers, unmanaged code, etc.). J2EE is rarely used in a non-enterprise environment to write graphically or numerically intensive code for executables.
28. What benefit do you have by implementing IDisposable interface in .NET?
You can use Dispose to clean up unmanaged resources.
29. Explain the difference between the Application object and Session object in ASP.NET.
The Application object affects all users of the application whereas a session only affects one (the session holder).
30. Explain the difference between User controls and Custom controls in ASP.NET.
From http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon/html/vbconwebusercontrolsvscustomwebcontrols.asp
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

31. Write code for transaction control in ADO.NET.
string connectionString = ".........";
SqlConnection myConnection = new SqlConnection(connectionString);
myConnection.Open();

// Start transaction.
SqlTransaction myTransaction = myConnection.BeginTransaction();

// Assign command in the current transaction.
SqlCommand myCommand = new SqlCommand();
myCommand.Transaction = myTransaction;
try
{
//db ops here.
myTransaction.Commit();
Console.WriteLine("Records are modified in the database.");
}
catch(Exception e)
{
myTransaction.Rollback();
Console.WriteLine(e.ToString());
Console.WriteLine("Neither record was written to database.");
}
finally
{
myConnection.Close();
}
32. Write code for transaction control in SQL Server.
BEGIN TRAN A
UPDATE mytable
BEGIN TRAN B WITH MARK
UPDATE mytable2
SELECT * frommytable
COMMIT TRAN B
UPDATE mytable3 ...
33. In .NET, what is an application domain?
From (Google Web Definitions)
A secure unit of processing that the Common Language Runtime uses to provide isolation between applications.
34. In SQL Server, what is an index?
An index is a list of sorted record pointers based on a column. Having indexes on your database tables will speed up SELECT queries if it is properly applied. Indexes will take up some disk space and will slow down INSERT and UPDATE queries.
35. What is optimistic vs. pessimistic locking?
Optimistic locking -- that's where you assume things will go well and design your locks so that they handle conflicts as the exceptional case
Pessimistic locking -- the converse where you assume conflicts are likely and create some kind of reservation system where sections are locked while they are edited

36. What is the difference between a clustered and non-clustered index.
From http://www.dotnetspider.com/technology/kbpages/1140.aspx
- The difference is that, Clustered index is unique for any given table and we can have only one clustered index on a table. The leaf level of a clustered index is the actual data and the data is resorted in case of clustered index.Whereas in case of non-clustered index the leaf level is actually a pointer to the data in rows so we can have as many non-clustered indexes as we can on the db.
37. In terms of remoting what is CAO and SAO?
Server Activated Objects : Stateless - SinglecallThis object type is the most prevalent and is recommended by Microsoft for use as the primary remoting type. Server activated Singlecall objects hold no state, which makes them ideal for use with clustered web servers, object pooling, and all other sorts of useful things. Since there is no state held in the object, you have to pass all the data that the object needs to do its work on every call.Server Activated Objects : Stateful - SingletonThese objects are used when you need both a stateful object AND you need that objects data to persist over time and multiple instantiation. If 3 computers instance an SAO Singleton on a server, they will all get a reference to that same object. Singletons are commonly used to direct access to scarce resources and should generally be avoided when possible.Client Activated Objects : StatefulCAO Objects are used when you need an object to be stateful throughout its lifetime to its caller. CAO Objects persist data to their caller, however they are different from SAO Singletons in that multiple instantiations of a CAO will get brand new instances of that CAO each time.
38. Remoting uses MarshallByRefObject, what does this mean?
A reference is returned to the remote object.
39. Write some code to use reflection, remoting, threading, and thread synchronization.
Threads and remoteable object:
using System;
using System.Reflection;
using System.Threading;

namespace Example
{
public class allThreads
{
const int NUMBER_OF_OPS = 10;
const int SLEEP_TIME = 2000;

private int threadNumber;
static int threadGlobalDS;
static object lockVariable = "dummy";

public allThreads(int threadNumber)
{
this.threadNumber = threadNumber;
}

// Thread with critical data access section using lock and global object

public void threadMethod()
{
System.Console.WriteLine("Thread " + threadNumber.ToString() + " starting with Hashcode: " + Thread.CurrentThread.GetHashCode());
System.Console.WriteLine("------------------");

for (int i=1;i<=NUMBER_OF_OPS;i++) { System.Console.WriteLine("--> Thread " + threadNumber.ToString() + " performing operation " + i.ToString());
}

System.Console.WriteLine("--> Thread " + threadNumber.ToString() + " sleeping");
Thread.Sleep(SLEEP_TIME);

// Locking using a global variable
lock(lockVariable)
{
System.Console.WriteLine("--> Thread " + threadNumber.ToString() + " has a lock");

// Access critical data
threadGlobalDS = threadNumber;

System.Console.WriteLine("--> Thread " + threadNumber.ToString() + " sleeping");
Thread.Sleep(SLEEP_TIME);
}

System.Console.WriteLine("--> Thread " + threadNumber.ToString() + " sleeping");
Thread.Sleep(SLEEP_TIME);
}
}

// Producer and consumer example using Monitor

public class monitorThreads
{
const int SLEEP_TIME = 2000;
const int MAX_PRODUCED = 5;

private static int threadGlobalDS = 0;
private static int bufferCount = 1;
private static bool producing = true;
private static bool consuming = true;

public void monitorMethod1()
{
// Producer...

while(producing)
{
// Synch using monitor

/* Attempt to get an exclusive lock on this object
* Block otherwise */
Monitor.Enter(this);

if(bufferCount == 1)
{
/* Release the lock on this object and block
* the current thread until it reacquires the lock. */
Monitor.Wait(this);
}
threadGlobalDS +=1;

++bufferCount;

if (threadGlobalDS == MAX_PRODUCED)
{
producing = false;
}
/* Notify a thread in the waiting
* queue of a change in the locked object's state (this object). */
Monitor.Pulse(this);

// Releases the exclusive lock on this object.
Monitor.Exit(this);

System.Console.WriteLine("--> Producer sleeping");
Thread.Sleep(SLEEP_TIME);
}
}

public void monitorMethod2()
{
while(consuming)
{
// Consumer...

// Synch using monitor
Monitor.Enter(this);

if(bufferCount == 0)
{

Monitor.Wait(this);
}

--bufferCount;
System.Console.WriteLine("--> Consumed " + threadGlobalDS.ToString());

Monitor.Pulse(this);
Monitor.Exit(this);

if (!producing)
{
consuming = false;
}
}
}
}

// Class to be remoted

public class RemotingLoader : System.MarshalByRefObject
{

public RemotingLoader()
{
System.Console.WriteLine("New Client Added");
}

public SomeMetadata GetSomeMetadata(decimal userID)
{
// Create objects to thread
allThreads threadObj1 = new allThreads(1);
allThreads threadObj2 = new allThreads(2);
allThreads threadObj3 = new allThreads(3);

// Instanciate and spin off some of threads
Thread thread1 = new Thread(new ThreadStart(threadObj1.threadMethod));
Thread thread2 = new Thread(new ThreadStart(threadObj2.threadMethod));
Thread thread3 = new Thread(new ThreadStart(threadObj3.threadMethod));

thread1.Start();
thread2.Start();
thread3.Start();

// Show that thread1 is alive
if (thread1.IsAlive)
{
System.Console.WriteLine("*-> Thread 1 is alive");
}

// Abort thread1 and check again
thread1.Abort();

if (!thread1.IsAlive)
{
System.Console.WriteLine("*-> Thread 1 is dead");
}

// Monitor example
monitorThreads monitorObj = new monitorThreads();

// Instanciate and spin off some of threads
Thread monitorThread1 = new Thread(new ThreadStart(monitorObj.monitorMethod1));
Thread monitorThread2 = new Thread(new ThreadStart(monitorObj.monitorMethod2));

monitorThread1.Start();
monitorThread2.Start();

monitorThread1.Join();
monitorThread2.Join();
thread1.Join();
thread2.Join();
thread3.Join();

System.Console.WriteLine("*-> Finished");

return new SomeMetadata(1);
}
}

// Class to be serialized

[Serializable]
public class SomeMetadata
{
public Type objectType;
public ConstructorInfo [] info;
public MethodInfo [] methods;

private string objectName;

decimal remoteObjectID;

public SomeMetadata(decimal remoteObjectID)
{
objectType = this.GetType();
info = objectType.GetConstructors();
methods = objectType.GetMethods();
this.remoteObjectID = remoteObjectID;
}

public String Name
{
get { return objectName; }
set
{ this.objectName = value; }
}
}
}
Server
using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;

namespace Example
{
public class RemotingServer
{
public static void Main(String[] args)
{
// Register Channel
TcpServerChannel channel = new TcpServerChannel(9000);
ChannelServices.RegisterChannel(channel);

// Register Service Type
RemotingConfiguration.RegisterWellKnownServiceType(typeof(RemotingLoader),
"RemotingLoader", WellKnownObjectMode.SingleCall);

// Wait
System.Console.WriteLine("Press Any Key To Kill The Server");
System.Console.ReadLine();
}
}
}
Client
using System;
using System.Reflection;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;

namespace Example
{
public class RemotingClient
{
public static void Main(string[] args)
{
// Register channel and point to remote object
ChannelServices.RegisterChannel(new TcpClientChannel());
RemotingLoader loader = (RemotingLoader)Activator.GetObject(
typeof(RemotingLoader), "tcp://localhost:9000/RemotingLoader");

// Get a reference to the remote object
SomeMetadata objReference = loader.GetSomeMetadata(1);

// Display data from object
Console.WriteLine("");
Console.WriteLine("*--- Object Type ---*");
Console.WriteLine("");

Console.WriteLine(objReference.objectType);

Console.WriteLine("");
Console.WriteLine("*--- Constructor Info. ---*");
Console.WriteLine("");

foreach(ConstructorInfo consInfo in objReference.info)
{
Console.WriteLine(consInfo);
}

Console.WriteLine("");
Console.WriteLine("*--- Method Info. ---*");
Console.WriteLine("");

foreach(MethodInfo methodInfo in objReference.methods)
{
Console.WriteLine(methodInfo);
}

Console.WriteLine("");
Console.WriteLine("*--- Setting and getting a Remote Variable. ---*");
Console.WriteLine("");

objReference.Name = "Test Name";
Console.WriteLine(objReference.Name);

// Wait...
Console.ReadLine();
}
}
}


Misc

1. Can you prevent your class from being inherited by another class?
Yes. The keyword “sealed” will prevent the class from being inherited.
2. Explain the three tier or n-Tier model.
Presentation (UI), business (logic and underlying code) and data (from storage or other sources).
3. What is SOA?
Service Oriented Architecture. In SOA you create an abstract layer that your applications use to access various "services" and can aggregate the services. These services could be databases, web services, message queues or other sources. The Service Layer provides a way to access these services that the applications do not need to know how the access is done. For example, to get a full customer record, I might need to get data from a SGL Server database, a web service and a message queue. The Service layer hides this from the calling application. All the application knows is that it asked for a full customer record. It doesn't know what system or systems it came from or how it was retrieved.
4. Is XML case-sensitive?
Yes
5. Can you explain some differences between an ADO.NET Dataset and an ADO Recordset? (Or describe some features of a Dataset).
A DataSet can represent an entire relational database in memory, complete with tables, relations, and views. A DataSet is designed to work without any continuing connection to the original data source. Data in a DataSet is bulk-loaded, rather than being loaded on demand. There's no concept of cursor types in a DataSet. DataSets have no current record pointer You can use For Each loops to move through the data. You can store many edits in a DataSet, and write them to the original data source in a single operation. Though the DataSet is universal, other objects in ADO.NET come in different versions for different data sources.
ASP.NET
1. Explain the differences between Server-side and Client-side code?
Server-side code executes on the server. Client-side code executes in the context of the clients' browser.
2. What does the "EnableViewState" property do? Why would I want it on or off?
It allows page objects to save their state in a Base64 encoded string in the page HTML. One should only have it enabled when needed because it adds to the page size and can get fairly large for complex pages with many controls. (It takes longer to download the page).
3. What is the difference between Server.Transfer and Response.Redirect? Why would I choose one over the other?
Server.Transfer transfers excution directly to another page. Response.Redirect sends a response to the client and directs the client (the browser) to load the new page (it causes a roundtrip). If you don't need to execute code on the client, Transfer is more efficient.
4. What base class do all Web Forms inherit from?
The Page class (System.Web.UI.Page).
5. What does WSDL stand for? What does it do?
(Web Services Description Language). It describes the interfaces and other information of a web service.
6. Which WebForm Validator control would you use if you needed to make sure the values in two different WebForm controls matched?
CompareValidator Control.
7. What property must you set, and what method must you call in your code, in order to bind the data from some data source to the Repeater control?
You must set the DataSource property and call the DataBind method.


1. What is a satellite Assembly?
An assembly containing localized resources for another assembly.
2. In Object Oriented Programming, how would you describe encapsulation?
The separation of interface and implementation.
* Encapsulation describes the ability of an object to hide its data and methods from the rest of the world. (Google web definitions).

1. Can you store multiple data types in System.Array?
No.
2. What’s the difference between the System.Array.CopyTo() and System.Array.Clone()?
The first one performs a deep copy of the array, the second one is shallow. A shallow copy of an Array copies only the elements of the Array, whether they are reference types or value types, but it does not copy the objects that the references refer to. The references in the new Array point to the same objects that the references in the original Array point to. In contrast, a deep copy of an Array copies the elements and everything directly or indirectly referenced by the elements.
3. How can you sort the elements of the array in descending order?
By calling Sort() and then Reverse() methods.
4. What’s the .NET collection class that allows an element to be accessed using a unique key?
HashTable.
5. What class is underneath the SortedList class?
A sorted HashTable.
6. Will the finally block get executed if an exception has not occurred?­
Yes
7. Can you prevent your class from being inherited by another class?
Yes. The keyword “sealed” will prevent the class from being inherited
8. If a base class has a number of overloaded constructors, and an inheriting class has a number of overloaded constructors; can you enforce a call from an inherited constructor to a specific base constructor?
Yes, just place a colon, and then keyword base (parameter list to invoke the appropriate constructor) in the overloaded constructor definition inside the inherited class.
9. What’s a multicast delegate?
(See the first set of answers)
10. What’s the difference between // comments, /* */ comments and /// comments?
Single-line comments, multi-line comments, and XML documentation comments.
11. How do you generate documentation from the C# file commented properly with a command-line compiler?
Compile it with the /doc switch.
12. What debugging tools come with the .NET SDK?
.CorDBG – command-line debugger. To use CorDbg, you must compile the original C# file using the /debug switch. DbgCLR – graphic debugger. Visual Studio .NET uses the DbgCLR.
13. What does assert() method do?
In debug compilation, assert takes in a Boolean condition as a parameter, and shows the error dialog if the condition is false. The program proceeds without any interruption if the condition is true.
14. What’s the difference between the Debug class and Trace class?
Use Debug class for debug builds, use Trace class for both debug and release builds.
15. Why are there five tracing levels in System.Diagnostics.TraceSwitcher?
The tracing dumps can be quite verbose. For applications that are constantly running you run the risk of overloading the machine and the hard drive. Five levels range from None to Verbose, allowing you to fine-tune the tracing activities.
16. Where is the output of TextWriterTraceListener redirected?
To the Console or a text file depending on the parameter passed to the constructor.
17. How do you debug an ASP.NET Web application?
Attach the aspnet_wp.exe process to the DbgClr debugger.
18. What are three test cases you should go through in unit testing?
1. Positive test cases (correct data, correct output).
2. Negative test cases (broken or missing data, proper handling).
3. Exception test cases (exceptions are thrown and caught properly).
19. Can you change the value of a variable while debugging a C# application?
Yes. If you are debugging via Visual Studio.NET, just go to Immediate window.
20. What are advantages and disadvantages of Microsoft-provided data provider classes in ADO.NET?
SQLServer.NET data provider is high-speed and robust, but requires SQL Server license purchased from Microsoft. OLE-DB.NET is universal for accessing other sources, like Oracle, DB2, Microsoft Access and Informix. OLE-DB.NET is a .NET layer on top of the OLE layer, so it’s not as fastest and efficient as SqlServer.NET.
21. What is the wildcard character in SQL?
Let’s say you want to query database with LIKE for all employees whose name starts with La. The wildcard character is %, the proper query with LIKE would involve ‘La%’.
22. Explain ACID rule of thumb for transactions.
A transaction must be:1. Atomic - it is one unit of work and does not dependent on previous and following transactions.2. Consistent - data is either committed or roll back, no “in-between” case where something has been updated and something hasn’t.3. Isolated - no transaction sees the intermediate results of the current transaction).4. Durable - the values persist if the data had been committed even if the system crashes right after.
23. Between Windows Authentication and SQL Server Authentication, which one is trusted and which one is untrusted?
Windows Authentication is trusted because the username and password are checked with the Active Directory, the SQL Server authentication is untrusted, since SQL Server is the only verifier participating in the transaction.
24. What are the ways to deploy an assembly?
An MSI installer, a CAB archive, and XCOPY command.
25. What namespaces are necessary to create a localized application?
System.Globalization and System.Resources.
26. What is the smallest unit of execution in .NET?
An Assembly.