Month: June 2014

Microsoft SQL Server and TSQL Refresher

1. Normalization/denormalization – example? 1/2/3NF
1NF Primary Key and no repeating group of data
2NF No partial dependency of non-key field on one of the primary keys
3NF No partial dependency among non-key fields

http://www.tutorialspoint.com/sql/first-normal-form.htm
http://databases.about.com/od/administration/l/bldef_2nf.htm
http://www.tutorialspoint.com/sql/second-normal-form.htm
http://www.tutorialspoint.com/sql/third-normal-form.htm

2. Recovery Model?
Full: Transaction by transaction, restore to Point-in-Time by restore last database backup, then transaction logs.
Bulk Logged: Bulk operations not logged to speed things up. You can still restore to Point-in-Time if no bulk operation between last database or transaction log backup.
Simple: Only minimal logging to transaction log. No Point-in-Time restore. Anything happens you can only recover up to last database backup.

http://www.todo-backup.com/backup-resource/sql-backup-software/three-sql-server-recovery-models.htm
http://www.mssqltips.com/sqlservertutorial/5/sql-server-bulklogged-recovery-model/

3. Checkpoint – “For performance reasons, the Database Engine performs modifications to database pages in memory—in the buffer cache—and does not write these pages to disk after every change. Rather, the Database Engine periodically issues a checkpoint on each database. A checkpoint writes the current in-memory modified pages (known as dirty pages) and transaction log information from memory to disk and, also, records information about the transaction log.
The Database Engine supports several types of checkpoints: automatic, indirect, manual, and internal.”
http://msdn.microsoft.com/en-us/library/ms189573(v=sql.110).ASPX

4. Backup Database?
http://www.mssqltips.com/sqlservertutorial/24/creating-a-backup-using-sql-server-command-line-tsql/

BACKUP DATABASE AdventureWorks
TO DISK = ‘C:\AdventureWorks.BAK’
GO

BACKUP LOG AdventureWorks
TO DISK = ‘C:\AdventureWorks.TRN’
GO

Backup Log? ldf -> trn
BACKUP LOG AdventureWorks
TO DISK = ‘C:\AdventureWorks.TRN’
GO

BACKUP LOG AdventureWorks
TO DISK = ‘C:\AdventureWorks.TRN’
WITH PASSWORD = ‘Q!W@E#R$’
GO

BACKUP LOG AdventureWorks
TO DISK = ‘C:\AdventureWorks.TRN’
WITH STATS
GO

BACKUP LOG AdventureWorks
TO DISK = ‘C:\AdventureWorks.TRN’
WITH STATS = 1
GO

BACKUP LOG AdventureWorks
TO DISK = ‘C:\AdventureWorks.TRN’
WITH DESCRIPTION = ‘Log backup for AdventureWorks’
GO

http://www.mssqltips.com/sqlservertutorial/21/sql-server-backup-log-command/
http://www.mssqltips.com/sqlservertutorial/8/sql-server-transaction-log-backups/
http://www.mssqltips.com/sqlservertip/1318/automating-transaction-log-backups-for-all-sql-server-databases/

3. Error ‘TRUNCATE_ONLY’ is not a recognized BACKUP option. when running following command. Why?
DBCC SHRINKFILE(TestDBLog, 1)
BACKUP LOG TestDB WITH TRUNCATE_ONLY
DBCC SHRINKFILE(TestDBLog, 1)

ANS:
“No, it’s not supported any more in sql 2008, if you want to remove log chain (Without proper log backup), try to switch to simple recovery mode.”
(a) Get Around
ALTER DATABASE [TestDb] SET RECOVERY SIMPLE WITH NO_WAIT
DBCC SHRINKFILE(TestDbLog, 1)
ALTER DATABASE [TestDb] SET RECOVERY FULL WITH NO_WAIT
(b) Take proper log backup
BACKUP LOG [TestDb] TO DISK = N’C:\Backup\TestDb.bak’

http://social.msdn.microsoft.com/Forums/sqlserver/en-US/54e6e281-005a-4b07-8c85-3685441f4f3d/truncateonly-is-not-a-recognized-backup-option?forum=sqldatabaseengine
http://blog.sqlauthority.com/2010/05/03/sql-server-shrinkfile-and-truncate-log-file-in-sql-server-2008/

4. Shrink Database?
DBCC SHRINKDATABASE (UserDB, 10);
GO

http://msdn.microsoft.com/en-us//library/ms190488.aspx

5. Shrink Log file?
“To avoid filling up the transaction log of a database, routine backups are essential. Under the simple recovery model, log truncation occurs automatically after you back up the database, and under the full recovery model, after you back up the transaction log.”

USE DatabaseName
GO
DBCC SHRINKFILE(<TransactionLogName>, 1)
BACKUP LOG <DatabaseName>
DBCC SHRINKFILE(<TransactionLogName>, 1)
GO
http://blog.sqlauthority.com/2010/05/03/sql-server-shrinkfile-and-truncate-log-file-in-sql-server-2008/
http://msdn.microsoft.com/en-us/library/ms186865.aspx
6. Restore Database?

CASE 1: RESTORE with file move:
Step 1: Retrive the Logical file name of the database from backup.
RESTORE FILELISTONLY
FROM DISK = ‘D:BackUpYourBaackUpFile.bak’
GO

Step 2: Use the values in the LogicalName Column in following Step.
—-Make Database to single user Mode
ALTER DATABASE YourDB
SET SINGLE_USER WITH
ROLLBACK IMMEDIATE

—-Restore Database
RESTORE DATABASE YourDB
FROM DISK = ‘D:BackUpYourBaackUpFile.bak’
WITH MOVE ‘YourMDFLogicalName’ TO ‘D:DataYourMDFFile.mdf’,
MOVE ‘YourLDFLogicalName’ TO ‘D:DataYourLDFFile.ldf’

ALTER DATABASE YourDB SET MULTI_USER
GO

CASE 2: RESTORE Differential
RESTORE DATABASE AdventureWorks FROM DISK = ‘C:\AdventureWorks.BAK’ WITH NORECOVERY
GO
RESTORE DATABASE AdventureWorks FROM DISK = ‘C:\AdventureWorks.DIF’
GO

CASE 3. Restore Transaction Log, to point in time
RESTORE DATABASE NewDatabase
FROM DISK = ‘D: \BackupFiles\TestDatabaseFullBackup.bak’
WITH
MOVE ‘PreviousDatabase’ TO ‘D:\DataFiles \TestDatabase.mdf’,
MOVE ‘PreviousDatabase_log’ TO ‘D:\DataFiles \TestDatabase_Log.ldf’,
NORECOVERY

RESTORE LOG NewDatabase
FROM DISK = ”D: \BackupFiles\TestDatabase_TransactionLogBackup1.trn’
WITH NORECOVERY

RESTORE LOG NewDatabase
FROM DISK = ”D: \BackupFiles\ TestDatabase_TransactionLogBackup2.trn’
WITH NORECOVERY

RESTORE LOG NewDatabase
FROM DISK = ”D: \BackupFiles\ TestDatabase_TransactionLogBackup3.trn’
WITH NORECOVERY

RESTORE LOG NewDatabase
FROM DISK = ”D: \BackupFiles\ TestDatabase_TransactionLogBackup4.trn’
WITH RECOVERY

RESTORE LOG NewDatabase
FROM DISK = ”D: \BackupFiles\ TestDatabase_TransactionLogBackup4.trn’
WITH STOPAT = N’6/28/2007 4:01:45 PM’, RECOVERY

http://www.codeproject.com/Articles/513248/Dynamically-restore-full-and-all-transaction-log-b
http://www.techrepublic.com/blog/the-enterprise-cloud/restore-your-sql-server-database-using-transaction-logs/

7. RESTORE vs ATTACH?
“Attach” manually select mdf/ndf and ldf
RESTORE restores from BAK and TRN (log)

8. Do we have “Parametetrized View” in TSQL?
* Closest is inline table UDF
http://stackoverflow.com/questions/4498364/create-parameterized-view-in-sql-server-2008

9. Advantages and Disadvantages of Stored Procedures?
Pros
* Reduce network traffic
* Code re-use
* Single point of control
* Compiled on first run
* Protection against SQL Injection
* Easy to unit test on SQL layer.

Cons
* Most database vendors offer different flavors of SQL. M$ SQL’s TSQL, Oracle PL SQL…etc.
Application logic wrapped in application layer can be database vendor neutral. However, stored procedures syntax isn’t.
* If you’re using Microsoft SQL, ability to debug stored procedures from Query Analyzer in SQL 2000 and SQL Management Studio 2008 or later.
SQL 2005 is the one edition when this ability was removed.
* When you’re running .NET code in debugger, you can STEP INTO stored procedure’s definition – meaning you’d have to debug the stored procedure separately.

http://dumindag.wordpress.com/2009/11/03/advantages-and-disadvantages-of-using-stored-procedures/
http://blog.sqlauthority.com/2009/11/08/sql-server-stored-procedure-are-compiled-on-first-run-sp-taking-longer-to-run-first-time/
http://www.diaryofaninja.com/blog/2010/11/23/debugging-sql-queries-function-amp-stored-procedures-with-sql-management-studio
http://stackoverflow.com/questions/2016879/debugging-stored-procedures-in-management-studio
http://stackoverflow.com/questions/273437/how-do-you-debug-mysql-stored-procedures

10. Stored Procedure vs UDF’s?
* Stored Procedures are pre-compile objects which are compiled for first time and its compiled format is saved which executes (compiled code) whenever it is called.
But Function is compiled and executed every time when it is called.
* Stored Procedures can contain try-catch block, not in UDF’s
* Stored Procedure can have input+output parameters. UDF’s only input parameters.
* UDF’s must return a result, whether scalar or TABLE, which can be nested in SELECT or WHERE clause of another statement.

http://www.dotnet-tricks.com/Tutorial/sqlserver/7EDL150912-Difference-between-Stored-Procedure-and-Function-in-SQL-Server.html

11. Database Encryption – Transparent Data Encryption (TDE) – “TDE enables you to encrypt an entire database. Backups for databases that use TDE are also encrypted. TDE protects the data at rest, which means that the database’s data and log files are encrypted using the AES and 3DES encryption algorithms. TDE is completely transparent to the application and requires no coding changes to implement.”
http://sqlmag.com/database-security/sql-server-encryption-options
https://www.simple-talk.com/sql/database-administration/transparent-data-encryption/

12. Encrypt Column of Data
http://technet.microsoft.com/en-us/library/ms179331.aspx

13. Dynamic Management View?

14. Why CURSOR sucks?
“set-based processing”
“row-based processing” –> CURSOR, slow

15. Primary Key vs Unique Constraints
Primary Key:
Can be only one in a table
It never allows null values
Primary Key is unique key identifier and can not be null and must be unique.

Unique Key:
Can be more than one unique key in one table.
Unique key can have null values
It can’t be candidate key
Unique key can be null and may not be unique.

16. Primary Key vs Clustered Index?

17. The bitwise operators in SQL Server are:
& (Bitwise AND)
~ (Bitwise NOT)
| (Bitwise OR)
^ (Bitwise Exclusive OR)

http://www.mssqltips.com/sqlservertip/1218/sql-server-bitwise-operators-store-multiple-values-in-one-column/

18. Synonyms
“Changing the name of an table once an application has been deployed has traditionally been a difficult task in SQL Server 2000. The typical solution in SQL Server 2000 for referencing a different object was to use a View.”
But with renamed View, you can’t do INSERT
http://www.mssqltips.com/sqlservertip/1076/how-and-why-should-i-use-sql-server-2005-synonyms/
http://blog.sqlauthority.com/2008/01/07/sql-server-2005-introduction-and-explanation-to-synonym-helpful-t-sql-feature-for-developer/

19. char(255) vs varchar(255) vs varchar(MAX) http://www.codeproject.com/Messages/4486417/char-255-vs-varchar-255-vs-varchar-MAX.aspx
Note
* varchar has null termination character, char don’t
* varchar(MAX) = 8000 bytes, nvarchar(MAX=4000) = 8000 bytes

20. Why not varchar(MAX) instead of varchar(n) everywhere? Index Key size < 900 bytes
http://stackoverflow.com/questions/2091284/varcharmax-everywhere

21. TEXT, NTEXT vs VARCHAR(MAX)

http://geekswithblogs.net/johnsPerfBlog/archive/2008/04/16/ntext-vs-nvarcharmax-in-sql-2005.aspx

TEXT/NTEXT/IMAGE deprecated in SQL 2012: http://technet.microsoft.com/en-us/library/ms143729.aspx
22. DATALENGTH() to get data length in TEXT/NTEXT/IMAGE columns?

http://www.mssqltips.com/sqlservertip/1188/how-to-get-length-of-text-ntext-and-image-columns-in-sql-server/

23. Heap Table? Clustered vs Non-clustered vs Xml
Table without a clustered-index is called a “heap table”. A heap table has no sorted data thus SQL server has to scan the entire table in order to locate the data in a process called a “scan”. In the case of a clustered index the data are sorted on the key values (columns) of the index. SQL server is now able to locate the data by navigating down from the root node, to the branch and finally to the leaf nodes of the B-tree structure of the index, in a process called a “seek”. The later approach is much faster when you want to filter or sort the data you want to retrieve.
A non-clustered index, stored in separate location, containing only a subset of columns and a row locator to the table’s rows or to the clustered index’s key.

http://msdn.microsoft.com/en-us/library/ms175049.aspx
http://www.karafilis.net/sql-indexing-part2/

24. B-tree – a tree data structure that keeps data sorted and allows searches, sequential access, insertions, and deletions in logarithmic time. The B-tree is a generalization of a binary search tree in that a node can have more than two children
http://www.youtube.com/watch?v=coRJrcIYbF4&hd=1

25. IndexSeek vs. IndexScan, Selectivity/Cadinality http://www.bennadel.com/blog/1424-Exploring-The-Cardinality-And-Selectivity-Of-SQL-Conditions.htm
Cardinality of a column = # rows in table / # distinct values in that column
(Max Cardinality = 1.0, the closer it get to 1.0 the more selective)

26. ACID = ?

Atomic/Consistent/Isolated/Durable

http://en.wikipedia.org/wiki/ACID

27. Isolation Level –
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED|REPEATABLE READ|SERIALIZABLE
Read Uncommitted – Dirty read
Read Committed [Default] – Share lock (On rows matching WHERE clause only, not table lock) released as soon as read operation done but before transaction completed
Repeatable Read – An additional guarantee that any data read cannot change (i.e. it is repeatable) for the duration of the transaction.
It does this by maintaining the Shared lock (On rows matching WHERE clause only, not table lock) for the duration of the transaction (i.e. read done + transaction completed)
Can have Phantom rows.
Serializable – It prevents phantoms by taking a range lock or table level lock if range lock can’t be acquired (i.e. no index on the predicate column) for the duration of the transaction.
No phantoms.

http://blogs.msdn.com/b/sqlcat/archive/2011/02/20/concurrency-series-basics-of-transaction-isolation-levels.aspx
http://gavindraper.com/2012/02/18/sql-server-isolation-levels-by-example/

28. Shared/Update/Exclusive/Intent locks?

sp_lock to check realtime locking information.

Example of locking hint:
SELECT * FROM Person.Address WITH (HOLDLOCK|UPDLOCK)
WHERE AddressId < 2

Share Lock – multiple threads can acquire Share Lock on same piece of data concurrently
Update Lock – Only one update lock can be held on the data at one time, similar to an exclusive lock. But the difference here is that the update lock itself can’t modify the underlying data.
Intent lock – An intent lock indicates that SQL Server wants to acquire a shared (S) lock or exclusive (X) lock on some of the resources lower down in the hierarchy. For example, a shared intent lock placed at the table level means that a transaction intends on placing shared (S) locks on pages or rows within that table. Setting an intent lock at the table level prevents another transaction from subsequently acquiring an exclusive (X) lock on the table containing that page. Intent locks improve performance because SQL Server examines intent locks only at the table level to determine if a transaction can safely acquire a lock on that table. This removes the requirement to examine every row or page lock on the table to determine if a transaction can lock the entire table.

http://msdn.microsoft.com/en-us/library/ms175519%28v=sql.105%29.aspx
http://www.sqlteam.com/article/introduction-to-locking-in-sql-server
http://msdn.microsoft.com/en-us/library/ms187373.aspx
http://technet.microsoft.com/en-us/library/aa213039(v=sql.80).aspx
http://sqlblog.com/blogs/kalen_delaney/archive/2009/09/11/what-do-you-intend-with-that-lock.aspx

29. Pessimistic Lock and Optimistic Lock?
http://www.codeproject.com/Articles/114262/6-ways-of-doing-locking-in-NET-Pessimistic-and-opt

30. @@IDENTITY vs SCOPE_IDENTITY() vs IDENT_CURRENT

http://blog.sqlauthority.com/2007/03/25/sql-server-identity-vs-scope_identity-vs-ident_current-retrieve-last-inserted-identity-of-record/
31. CREATE TABLE, PK vs UNIQUE and general constraints, FILLFACTOR
PK: http://blog.sqlauthority.com/2007/10/16/sql-server-three-t-sql-script-to-create-primary-keys-on-table/
IF OBJECT_ID (‘dbo.Vendors’, ‘U’) IS NOT NULL
DROP TABLE dbo.Vendors;
GO
CREATE TABLE dbo.Vendors
(
VendorID int PRIMARY KEY,
VendorName nvarchar (50),
CreditRating tinyint,
Country char(3),

constrant CK_Vendor_CreditRating check(CreditRating>0 AND CreditRating<100)
)
GO

ALTER TABLE dbo.Vendors ADD CONSTRAINT CK_Vendor_CreditRating
CHECK (CreditRating > 0 AND CreditRating < 100)

CREATE NONCLUSTERED INDEX idx_VendorCountry on Vendors (Country)

CREATE [CLUSTERED|NONCLUSTERED] INDEX ix_tableName__columnName ON tableName (columnName)

CREATE TRIGGER (For auditing/validations) – http://msdn.microsoft.com/en-us/library/ms189799.aspx
CREATE TRIGGER reminder2
ON Sales.Customer
AFTER INSERT, UPDATE, DELETE
AS
EXEC msdb.dbo.sp_send_dbmail
@profile_name = ‘AdventureWorks2012 Administrator’,
@recipients = ‘danw@Adventure-Works.com’,
@body = ‘Don”t forget to print a report for the sales force.’,
@subject = ‘Reminder’;
32. UDF
– Scalar functions
– Inline Table-valued functions
– Multi-statement Table-valued functions

CREATE FUNCTION [dbo].[ufn_GetContactOrders](@ContactID int)
RETURNS varchar(500)
AS
BEGIN
DECLARE @Orders varchar(500)
SELECT @Orders = COALESCE(@Orders + ‘, ‘, ”) + CAST(SalesOrderID as varchar(10)) WHERE ContactID = @ContactID
RETURN (@Orders)
END

CREATE FUNCTION [dbo].[ufn_itv_GetContactSales](@ContactID int)
RETURNS TABLE
AS
RETURN (
SELECT h.[ContactID], h.[SalesOrderID], p.[ProductID], p.[Name], h.[OrderDate], h.[DueDate],
h.[ShipDate], h.[TotalDue], h.[Status], h.[SalesPersonID]
FROM Sales.SalesOrderHeader AS h
JOIN Sales.SalesOrderDetail AS d ON d.SalesOrderID = h.SalesOrderID
JOIN Production.Product AS p ON p.ProductID = d.ProductID
WHERE ContactID = @ContactID )

CREATE FUNCTION [dbo].[ufn_mtv_GetContactSales](@ContactID int)
RETURNS @retSalesInfo TABLE (
[ContactID] INT NOT NULL,
[SalesOrderID] INT NULL,
[ProductID] INT NULL,
[Name] NVARCHAR(50) NULL,
[OrderDate] DATETIME NULL,
[DueDate] DATETIME NULL,
[ShipDate] DATETIME NULL,
[TotalDue] MONEY NULL,
[Status] TINYINT NULL,
[SalesPersonID] INT NULL)
AS
BEGIN
IF @ContactID IS NOT NULL
BEGIN
INSERT @retSalesInfo
SELECT h.[ContactID], h.[SalesOrderID], p.[ProductID], p.[Name], h.[OrderDate], h.[DueDate],
h.[ShipDate], h.[TotalDue], h.[Status], h.[SalesPersonID]
FROM Sales.SalesOrderHeader AS h
JOIN Sales.SalesOrderDetail AS d ON d.SalesOrderID = h.SalesOrderID
JOIN Production.Product AS p ON p.ProductID = d.ProductID
WHERE ContactID = @ContactID
END
— Return the recordsets
RETURN
END

http://sqlwithmanoj.wordpress.com/2010/12/11/udf-user-defined-functions/
33. CURSOR types [ STATIC | KEYSET | DYNAMIC | FAST_FORWARD ]
http://www.sql-server-performance.com/2007/cursors/

34. CTE

A common table expression (CTE) is a temporary named result set that can be used within other statements like SELECT, INSERT, UPDATE, and DELETE. It is not stored as an object and its lifetime is limited to the query. It is defined using the WITH statement as the following example shows:

WITH ExampleCTE (id, fname, lname)
AS
(
SELECT id, firstname, lastname FROM table
)
SELECT * FROM ExampleCTE

http://sqlwithmanoj.wordpress.com/2011/05/23/cte-recursion-sequence-dates-factorial-fibonacci-series/
35. Ranking functions ROW_NUMBER,RANK,DENSE_RANK,NTILE:
Example 1: Simple ROW_NUMBER

WITH OrderedOrders AS
(
SELECT SalesOrderID, OrderDate,
ROW_NUMBER() OVER (ORDER BY OrderDate) AS RowNumber
FROM Sales.SalesOrderHeader
)
SELECT SalesOrderID, OrderDate, RowNumber
FROM OrderedOrders
WHERE RowNumber BETWEEN 50 AND 60;

Example 2: PARTITION
SELECT FirstName, LastName, TerritoryName, ROUND(SalesYTD,2,1),
ROW_NUMBER() OVER(PARTITION BY TerritoryName ORDER BY SalesYTD DESC) AS Row
FROM Sales.vSalesPerson
WHERE TerritoryName IS NOT NULL AND SalesYTD <> 0
ORDER BY TerritoryName;

WHERE vs HAVING
WHERE is applied before GROUPBY, HAVING is applied after.

SELECT Employees.LastName, COUNT(Orders.OrderID) AS NumberOfOrders FROM (Orders
INNER JOIN Employees
ON Orders.EmployeeID=Employees.EmployeeID)
GROUP BY LastName
HAVING COUNT(Orders.OrderID) > 10;

http://msdn.microsoft.com/en-us/library/ms175126.aspx
http://sqlwithmanoj.wordpress.com/2010/08/09/ranking-functions-with-sql-server-2005/
http://thehobt.blogspot.hk/2009/02/rownumber-rank-and-denserank.html
http://markvsql.com/2009/02/the-coolness-of-the-t-sql-ntile-function/

36. PIVOT

create table DailyIncome(VendorId nvarchar(10), IncomeDay nvarchar(10), IncomeAmount int)
— insert some sample data
select * from DailyIncome
pivot (avg (IncomeAmount) for IncomeDay in ([MON],[TUE],[WED],[THU],[FRI],[SAT],[SUN])) as AvgIncomePerDay

CUBE,ROLLUP,GROUPING SET http://sqlwithmanoj.wordpress.com/2010/11/12/cube-rollup-compute-compute-by-grouping-sets/
select class, section, sum(marks) [sum]
from #tempTable
group by class, section [with CUBE|ROLLUP]

TRUNCATE vs DELETE – TRUNCATE reset IDENTITY

ISNULL vs NULLIF http://blog.sqlauthority.com/2007/06/22/sql-server-explanation-and-comparison-of-nullif-and-isnull/
ISNULL – returns replacement if arg1 is NULL
select isnull(NULL, ‘N/A’) –> Returns ‘N/A’
NULLIF – returns null if arg1 and arg2 equals
select nullif(‘abc’, ‘abc’) –> Returns null

ISNULL vs COALESCE http://sqlwithmanoj.wordpress.com/2010/12/23/isnull-vs-coalesce/
DECLARE @str1 VARCHAR(10), @str2 VARCHAR(10)

— ISNULL() takes only 2 arguments
SELECT ISNULL(@str1, ‘manoj’) AS ‘IS_NULL’ — manoj

— COALESCE takes multiple arguments and returns first non-NULL argument
SELECT COALESCE(@str1, @str2, ‘manoj’) AS ‘COALESCE’ — manoj

— ISNULL() equivalent of COALESCE, by nesting of ISNULL()
SELECT ISNULL(@str1, ISNULL(@str2, ‘manoj’)) AS ‘IS_NULL eqv’ — manoj

EXECUTE vs sp_executesql (OUTPUT) http://support.microsoft.com/kb/262499
SET @SQLString = N’SELECT @LastlnameOUT = max(lname)
FROM pubs.dbo.employee WHERE job_lvl = @level’
SET @ParmDefinition = N’@level tinyint,
@LastlnameOUT varchar(30) OUTPUT’
SET @IntVariable = 35
EXECUTE sp_executesql
@SQLString,
@ParmDefinition,
@level = @IntVariable,
@LastlnameOUT=@Lastlname OUTPUT
http://blogs.msdn.com/b/spike/archive/2009/03/03/pivot-tables-in-sql-server-a-simple-sample.aspx

37. Send email alerts? sp_send_dbmail
Execute operating system command?
insert into exec xp_cmdshell ‘dir c:\*.exe’

38. GETDATE (ms) vs SYSDATETIME (nano sec)

http://blog.sqlauthority.com/2010/06/10/sql-server-difference-between-getdate-and-sysdatetime/

39. INTERSECT and EXCEPT

http://www.mssqltips.com/sqlservertip/1327/compare-sql-server-datasets-with-intersect-and-except/

40. TRY-CATCH, ERROR_MESSAGE,ERROR_NUMBER,ERROR_SEVERITY, RAISEERROR
@UserName = SUSER_SNAME(),
@HostName = HOST_NAME(),
@Time_Stamp = GETDATE();
CASE statement
SELECT
FirstName, LastName,
Salary, DOB,
CASE Gender
WHEN ‘M’ THEN ‘Male’
WHEN ‘F’ THEN ‘Female’
END
FROM Employees

http://www.mssqltips.com/sqlservertip/1027/sql-server-2005-try-and-catch-exception-handling/
http://www.mssqltips.com/sqlservertip/1152/standardized-sql-server-error-handling-and-centralized-logging/
http://msdn.microsoft.com/en-us/library/ms178592%28v=sql.90%29.aspx

41. GO statement and multiple batches – what’s it for?
http://www.mssqltips.com/sqlservertip/1216/executing-a-tsql-batch-multiple-times-using-go/

http://technet.microsoft.com/en-us/library/ms188037.aspx

42. CREATE SYNONYM

http://blog.sqlauthority.com/2008/01/07/sql-server-2005-introduction-and-explanation-to-synonym-helpful-t-sql-feature-for-developer/

43. DELETE duplicates on table with no PK via SET ROWCOUNT

http://www.mssqltips.com/sqlservertip/1103/delete-duplicate-rows-with-no-primary-key-on-a-sql-server-table/

44. Performance Tuning
DBCC DBREINDEX – deprecated, use ALTER INDEX instead.
http://msdn.microsoft.com/en-us/library/ms181671.aspx

Change from:
DBCC DBREINDEX(‘$TABLENAME$,’ ‘,0.75)
To:
ALTER INDEX PK_Employee_EmployeeID ON HumanResources.Employee
REBUILD;

ALTER INDEX ALL ON ‘$TABLENAME$’ REBUILD WITH (FILLFACTOR = 0.75)
http://www.mssqltips.com/sqlservertip/1367/sql-server-script-to-rebuild-all-indexes-for-all-tables-and-all-databases/

DBCC INDEXDEFRAG – Defrag index, deprecated, use ALTER INDEX instead: http://msdn.microsoft.com/en-us/library/ms177571.aspx

DBCC SHOWCONTIG – Shows fragmentation statistics. Deprecated, use “sys.dm_db_index_physical_stats” instead.
http://msdn.microsoft.com/en-us/library/ms175008.aspx
http://msdn.microsoft.com/en-us/library/ms188917.aspx

DECLARE @db_id SMALLINT;
DECLARE @object_id INT;
SET @db_id = DB_ID(N’AppliedAlgoDb’);
SET @object_id = OBJECT_ID(N’PK_DownloadStats’);
SELECT * FROM sys.dm_db_index_physical_stats(@db_id, @object_id, NULL, NULL , ‘LIMITED’);

Query Execution Plan –> Specific Query: Look for Table Scan. Issues with JOIN’s? Percent Cost…etc
https://www.youtube.com/watch?v=J69zLvoh2oI
http://www.mssqltips.com/sqlservertip/1873/how-to-read-sql-server-graphical-query-execution-plans/
http://technet.microsoft.com/en-us/library/ms175913(v=sql.105).aspx

SQL Profiler –> Look for queries which hits many times, or queries which takes long time to run. Issues with JOIN’s?

Database Engine Tuning Advisor –> Give a workload, create statistics & indexes
https://www.youtube.com/watch?v=xzXNRWuzIyE

Perfmon – Disk Activity?
Excessive paging can be observed via Perfmon. Add Counter: LogicalDisk\Avg Queue Length\_Total
(If reading >2 consistently, you probably need to review your job )

45. Audit
a. Server role member

EXEC sp_helpsrvrolemember

b. Following run against sys views in User database (not Master database)

Table schema

select
TableList.TABLE_SCHEMA as SchemaName,
TableList.TABLE_NAME as TableName,
COL.COLUMN_NAME as ColumnName,
COL.ORDINAL_POSITION as OrdinalPosition,
COL.COLUMN_DEFAULT as ColumnDefault,
COL.IS_NULLABLE as IsNullable,
COL.DATA_TYPE as DataType,
COL.CHARACTER_MAXIMUM_LENGTH as CharMaxLength,
COL.NUMERIC_PRECISION as NumericPrecision,
COL.DATETIME_PRECISION as DateTimePrecision,
COL.CHARACTER_SET_NAME as CharSetName,
COL.COLLATION_NAME as CollationName
FROM INFORMATION_SCHEMA.COLUMNS COL
join (
select
distinct TABLE_SCHEMA, TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS
) TableList on TableList.TABLE_NAME = COL.TABLE_NAME and TableList.TABLE_SCHEMA = COL.TABLE_SCHEMA
order by TableList.TABLE_SCHEMA, TableList.TABLE_NAME, COL.ORDINAL_POSITION

Table size

SELECT
sch.name SchemaName,
t.name TableName,
p.rows rowcnt,
SUM(a.total_pages) * 8 as TotalSpaceKB,
SUM(a.used_pages) * 8 as UsedSpaceKB,
(SUM(a.total_pages) – SUM(a.used_pages)) * 8 as UnusedSpaceKB
FROM sys.tables t
JOIN sys.schemas sch on t.schema_id = sch.schema_id
JOIN sys.indexes i on t.object_id = i.object_id
JOIN sys.partitions p on i.object_id = p.object_id and i.index_id = p.index_id
JOIN sys.allocation_units a ON p.partition_id = a.container_id

where
t.is_ms_shipped = 0
and i.object_id>255

group by sch.name, t.name, p.rows
order by p.rows desc
List views

select
sch.name as SchemaName,
vws.name as ViewName,
vws.create_date as CreateDate,
vws.modify_date as ModifyDate
from sys.views as vws
join sys.schemas as sch on vws.schema_id = sch.schema_id
order by sch.name, vws.name
View Scheuma

select
sch.name as SchemaName,
vws.name as ViewName,
col.column_id as ColumnId,
col.name as ColumnName
from sys.views as vws
join sys.schemas sch on vws.schema_id = sch.schema_id
join sys.columns col on vws.object_id = col.object_id
order by sch.name, vws.name
Audit Stored Procedures and definitions

select
distinct
ROUTINE_NAME as RoutineName,
ROUTINE_SCHEMA as SchemaName,
ROUTINE_TYPE as RoutineType,
CREATED as CreateDate,
LAST_ALTERED as ModifyDate,
ROUTINE_DEFINITION as RoutineDefinition
FROM INFORMATION_SCHEMA.ROUTINES
order by ROUTINE_SCHEMA, LAST_ALTERED

Happy Coding!

Advertisements

Technical Interviews – .NET Developers

Some of them may sound silly, does not reflect upon your level of intelligence, others may not be relevant to your job, yet some are designed just to filter experienced candidates who can do the job. Just make sure you have the right answer before walking into the room, that how the system works. This said, some of these are actually things you’d need to know 🙂

1. What gets printed?

string[] SomeListOfNames = {“Doe”, “Doddie”, “Susan”, “Mary”};
var q = from Name in SomeListOfNames
select Name;

SomeListOfNames[0] = “John Doe”;
foreach (string Person in q)
{
Console.WriteLine(Person);
}

ANS: John Doe, Doddie, Susan, Mary

 

2. Lambda and variable scope:
static int TestFunc(ref int i, int j)
{
SomeFunc deg = (int num) =>
{
int k = 50;
if (i > 0) // Annonymous method can access “i” outside its body (But this won’t compile as “int i” passed in as “ref”!
{
while (i > 0)
{
num++;
i–;
}
}
else
{
SomeFunc deg2 = (int num2) =>
{
while (k > 0) // Annonymous method can access “k” outside its body
{
num2 += z;
k–;
}
return num2;
};
num = deg2(num);
}

return num++;
};
j = deg(j);

return j * 10;
}

static void Main(string[] args)
{
int i = -1;
int j = 0;
int k = TestFunc(ref i, j); <– “i” passed in as “ref”. Lambda can’t access it.
}

Annonymous Method – variable scope? Further, no “ref”, or “out”! No unsafe code.
Quote MSDN:
a. An anonymous method cannot access the ref or out parameters of an outer scope.
b. No unsafe code can be accessed within the anonymous-method-block.
c. Anonymous methods are not allowed on the left side of the is operator.

Also, important to remember, compiler generate class to hold the annonymous method.
http://msdn.microsoft.com/en-us/library/0yw3tz5k.aspx
http://stackoverflow.com/questions/2890987/scope-of-variables-inside-anonymous-functions-in-c-sharp
http://www.codeproject.com/Articles/155756/Anonymous-Methods-Behind-the-Scenes

 

3. If you instantiate Z, what gets printed?
class X
{
Y a = new Y(); <- #2
public X()
{
Console.Write(“X”); <- #3
}
}

class Y
{
public Y()
{
Console.Write(“Y”);
}
}

class Z : X
{
Y b = new Y(); <- #1
public Z()
{
Console.Write(“Z”); <- #4
}
}

ANS: YYXZ

 

4. private virtual/abstract method?
class X
{
private virtual void Test()
{
return;
}

Y b = new Y();
public X()
{
Console.Write(“X”);
}
}

ANS: Compile error, “virtual or abstract members cannot be private”

 

5. Will this compile? Y overrides a method in X which isn’t marked virtual

class X
{
private void Shout() // marking “private virtual” will give compiler error
{
Console.WriteLine(“X.Shout”);
}
}

class Y
{
public override void Shout() // If base class didn’t have “virtual void Shout” also would give compile error if you “override” here.
{
Console.WriteLine(“Y.Shout”);
}
}

ANS: “no suitable method found to override”

 

6.

Which can access X.num?
class X
{
private int num = 999;

class Nested
{
public int GetNum(X x)
{
return x.num; //OK
}
}
}

class Y : X
{
class Nested
{
public int GetNum(X x)
{
return x.num; // Compile error
}
}
}

Which can access X.num now?
class X
{
protected int num = 999; <– protected, not private as in prev question

class Nested
{
public int GetNum(X x)
{
return x.num; //OK
}
}
}

class Y : X
{
class Nested
{
public int GetNum(X x) <– to compile, change to “GetNum(Y x)
{
return x.num; // Compile error
}
}
}

 

7. What’s the use of “new” keyword? “new” vs “override”?

class Car
{
public virtual void DescribeCar()
{
System.Console.WriteLine(“Four wheels and an engine.”);
}
}

// Define the derived classes
class ConvertibleCar : Car
{
public void DescribeCar() <– For example, code WILL COMPILE SUCCESSFULLY even if you don’t mark method “new”, but you get Warning 3 ‘SimpleConsole.ConvertibleCar.DescribeCar()’ hides inherited member ‘SimpleConsole.Car.DescribeCar()’. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword.
{
System.Console.WriteLine(“A roof that opens up.”);
}
}

class Minivan : Car
{
public override void DescribeCar()
{
System.Console.WriteLine(“Carries seven people.”);
}
}

Car car1 = new Car();
car1.DescribeCar();

ConvertibleCar car2 = new ConvertibleCar();
car2.DescribeCar(); <– overridden ConvertibleCar.DescribeCar will be called

Minivan car3 = new Minivan();
car3.DescribeCar(); <– overridden Minivan.DescribeCar will be called

Car[] cars = new Car[3];
cars[0] = new Car();
cars[1] = new ConvertibleCar();
cars[2] = new Minivan();
foreach (Car vehicle in cars)
{
vehicle.DescribeCar(); <– No Polymorphism for cars[1] which is a ConvertibleCar.
}

Console.WriteLine(“Hit any key to exit”);
Console.ReadLine();

http://msdn.microsoft.com/en-us/library/ms173153%28v=vs.80%29.aspx

 

8. const vs readonly
ANS: “The only difference is that const variables are defined in compile time, while readonly variables are defined at runtime during object initialization. You can assign readonly variables from within constructors, so based on the constructor call you may assign readonly values differently.”
http://www.codeproject.com/Articles/38695/UnCommon-C-keywords-A-Look#dcr

 

9. Struct vs Class differences
http://www.jaggersoft.com/pubs/StructsVsClasses.htm
Note in particular struct can implement interfaces (http://blogs.msdn.com/b/abhinaba/archive/2005/10/05/477238.aspx), but doesn’t support inheritance.
 

10. Access to “protected internal” members?
* Same Assembly?
* Nested class?
http://www.codeproject.com/Articles/25078/C-Access-Modifiers-Quick-Reference

 

11. What gets printed?
IList<string> SomeList = new List<string>();
SomeList.Add(“AAA”);
SomeList.Add(“BBB”);
SomeList.Add(“CCC”);
SomeList.Add(“DDD”);
SomeList.Add(“EEE”);

string[] Clone = SomeList.ToArray<string>();
Clone[0] = “ZZZ”;

Console.WriteLine(SomeList[0]); // AAA
Console.WriteLine(Clone[0]); // ZZZ

 

12. What gets printed?
Shallow vs Deep Copy? A shallow copy can be made by simply copying the reference.

IList<Person> SomeList = new List<Person>();
SomeList.Add(new Person() { Name = “John” });
SomeList.Add(new Person() { Name = “Peter” });
SomeList.Add(new Person() { Name = “Wayne” });

Person[] Clone = new Person[3];
SomeList.CopyTo(Clone, 0); // With “CopyTo”, you’d always need preallocate destination array
Clone[0].Name = “Mary”;

Console.WriteLine(SomeList[0].Name); // Mary
Console.WriteLine(Clone[0].Name); // Mary

Person[] Clone2 = null;
Clone2 = Clone.Clone() as Person[];
Person First = Clone2[0];
First.Name = “Jane”;

Console.WriteLine(SomeList[0].Name); // Jane
Console.WriteLine(Clone[0].Name); // Jane
Console.WriteLine(Clone2[0].Name); // Jane

Person[] Clone3 = new Person[3];
Clone.CopyTo(Clone3, 0); // With “CopyTo”, you’d always need preallocate destination array
Clone3[0].Name = “Jean”;

Console.WriteLine(SomeList[0].Name); // Jean
Console.WriteLine(Clone[0].Name); // Jean
Console.WriteLine(Clone2[0].Name); // Jean
Console.WriteLine(Clone3[0].Name); // Jean

Person SomePerson = (from p in Clone3
select p).FirstOrDefault<Person>();
SomePerson.Name = “Marco”;
Console.WriteLine(SomeList[0].Name); // Macro
Console.WriteLine(Clone[0].Name); // Macro
Console.WriteLine(Clone2[0].Name); // Macro
Console.WriteLine(Clone3[0].Name); // Macro

ANS: CopyTo or Clone: It’s always a Shallow Copy.

 

13. “partial” classes – real use
http://www.codeproject.com/Articles/313352/4-real-time-use-of-Partial-classes-and-partial-met#Fundamentalsofpartialclasses
Example 1: ASP.NET
AppliedAlgoWeb.aspx + AppliedAlgoWeb.aspx.cs + AppliedAlgoWeb.aspx.designer.cs
Example 2: LINQ to SQL
AppliedAlgoDb.dbml + AppliedAlgoDb.cs + AppliedAlgoDb.designer.cs

 

14. Nullable types – i.e. System.Nullable<T> – is it value type? or reference type?

bool? bTmp = null;
System.Nullable<bool> bTmp2 = null; // alternatively…
bTmp = false;
if (bTmp.HasValue)
{
if (bTmp == true)
{
Console.Write(“Yes!”);
}
else
{
Console.Write(“No!”);
}
}

ANS: It’s a “struct” (i.e. value type or System.ValueType), so not Reference type.

 

15. struct can implement Interface?
struct Person : IPerson
{
public string Name { get; set; }
}

interface IPerson
{
string Name { get; set; }
}
ANS: Yes! http://blogs.msdn.com/b/abhinaba/archive/2005/10/05/477238.aspx

 

16. Event vs Delegates – Why Events when you have delegates?

ANS: Events are like properties, instead of get/set, we have add/remove
http://csharpindepth.com/Articles/Chapter2/Events.aspx

 

17. Events – how to safe guard against null reference when invocation list is null?

ANS:
public delegate void OnRequestReceivedHandler(object sender);
public event OnRequestReceivedHandler ReqeustReceived = delegate { };

http://www.akadia.com/services/dotnet_delegates_and_events.html

 

18. foreach – IEnumerable? Or IEnumerator
ANS: IEnumerable
* IEnumerable is an interface enforcing a rule that we need to implement the GetEnumerator method.
* GetEnumerator method returns an IEnumerator interface.

http://www.codeproject.com/Articles/571139/Foreach-On-IEnumerable

 

19. What are the different ways to parse and manipulate XML?

Example 1: XmlReader http://www.dotnetperls.com/xmlreader
using (FileStream fileSteam = File.OpenRead(fileName))
{
XmlReaderSettings settings;
settings = new XmlReaderSettings();
settings.ConformanceLevel = ConformanceLevel.Document;

using(XmlReader reader = XmlReader.Create(fileSteam, settings))
{
while (reader.Read())
{
// reader.Name|Value
}
}
}

Example 2: XmlDocument (Editable, forward/backward anything you like)
XmlDocument vs XPathDocument: http://msdn.microsoft.com/en-us/library/eh3exdc4(v=vs.110).aspx

XmlDocument xml = new XmlDocument();
xml.LoadXml(myXmlString); // suppose that myXmlString contains “<Names>…</Names>”

XmlNodeList xnList = xml.SelectNodes(“/Names/Name”); <– SelectNodes takes an XPath
foreach (XmlNode xn in xnList)
{
string firstName = xn[“FirstName”].InnerText;
string lastName = xn[“LastName”].InnerText;
Console.WriteLine(“Name: {0} {1}”, firstName, lastName);
}

Example 3: XPath (Read only, forward/backward anything you like)
XPathDocument xmlDoc = new XPathDocument(Rdr);
XPathNavigator Nav = xmlDoc.CreateNavigator();
XPathNodeIterator Iter = Nav.Select(“/SERIALIZER_ROOT/SERIALIZER_OBJECT”);
while (Iter.MoveNext())
{
// Iter.Current.Value|InnerText|InnerXml
// Iter.Current.GetAttribute($ATTRIBNAME$)
}

Example 4: System.Xml.Linq – http://www.dotnetcurry.com/showarticle.aspx?ID=564
strXml = System.IO.File.ReadAllText(“Sample.xml”);
var Customers = from Customer in System.Xml.Linq.XElement.Parse(strXml).Element(“Customers”).Elements(“Customer”)
where Customer.Element(“FullAddress”).Element(“Country”).Value == “Canada”
select Customer;
foreach (var Customer in Customers)
{
Console.WriteLine(Customer.ToString());
}

Example 5. Parse using DynamicXmlStream, derived from System.Dynamic.DynamicObject – http://www.codeproject.com/Articles/436406/Power-of-Dynamic-Reading-XML-and-CSV-files-made-ea
dynamic customerOrderXmlReader = DynamicXmlStream.Load(new FileStream(“../../Input/CustomerOrder.xml”, FileMode.Open));
Console.WriteLine(“First Customer’s Company Name = ” + customerOrderXmlReader.Root.Customers.Customer[0].CompanyName.Value);

Basically, “DynamicXmlStream” extends “System.Dynamic.DynamicObject”, you’d need override:
bool TryGetMember(GetMemberBinder binder, out object result)
bool TrySetMember(SetMemberBinder binder, object value)
bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result)
bool TrySetIndex(SetIndexBinder binder, object[] indexes, object value)
bool TryConvert(ConvertBinder binder, out object result)
bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)

 

20. abstract vs interface – http://www.codeproject.com/Articles/6118/All-about-abstract-classes
abstract method cannot be private/static/virtual
abstract class cannot be sealed
abstract class can contain abstract+non-abstract properties and methods
(Abstract class can have zero abstract methods or properties)
Purpose?
* abstract class is to declare core functionalities to be implemented by derived classes.
* interface is for peripheral.

 

21. Implement multiple interface with name conflict?

ANS:
interface IShow
{
void Show();
}
interface IShow_Case
{
void Show();
}
class B : IShow, IShow_Case
{
public void IShow.Show()
{
Console.WriteLine(“IShow Interface function”);
}
public void IShow_Case.Show()
{
Console.WriteLine(“IShow_Case Interface function”);
}

static void Main(string[] args)
{
IShow I = new B();
I.Show();
IShow_Case I1 = new B();
I1.Show();
Console.ReadKey(true);
}
}

http://www.c-sharpcorner.com/Blogs/12431/inherit-multiple-interfaces-and-they-have-conflicting-method.aspx

 

22. Stack vs Heap
a. Both in RAM
b. Stack much faster
c. Each thread has its own Stack, all threads shared same heap
d. Value types on Stack and Reference types on heap? — This is false!
What about a “struct” instantiated with “new” operator?
* Each local variable (ie one declared in a method) is stored on the stack. That includes reference type variables – the variable itself is on the stack, but remember that the value of a reference type variable is only a reference (or null), not the object itself. Method parameters count as local variables too, but if they are declared with the ref modifier, they don’t get their own slot, but share a slot with the variable used in the calling code. See my article on parameter passing for more details.
* Instance variables for a reference type are always on the heap. That’s where the object itself “lives”.
* Instance variables for a value type are stored in the same context as the variable that declares the value type. The memory slot for the instance effectively contains the slots for each field within the instance. That means (given the previous two points) that a struct variable declared within a method will always be on the stack, whereas a struct variable which is an instance field of a class will be on the heap.
* Every static variable is stored on the heap, regardless of whether it’s declared within a reference type or a value type. There is only one slot in total no matter how many instances are created. (There don’t need to be any instances created for that one slot to exist though.)

http://yoda.arachsys.com/csharp/memory.html
http://www.programmerinterview.com/index.php/data-structures/difference-between-stack-and-heap/
http://www.c-sharpcorner.com/UploadFile/rmcochran/csharp_memory01122006130034PM/csharp_memory.aspx
https://www.simple-talk.com/dotnet/.net-framework/large-object-heap-compaction-should-you-use-it (Large Object Heap and .NET 4.5 enhancements to support admin of LOH)
 

23. GC – Application wide? Or System wide?
ANS: Each application has its own GC processing.

http://stackoverflow.com/questions/6982409/is-the-garbage-collector-in-net-system-wide-or-application-wide
http://stackoverflow.com/questions/11189932/stack-and-heap-allocation

 

24. What’s GC Gen 0/1/2?
ANS: Garbage Collection – Generation 0 (Newest), 1 (Survive one GC pass), 2 (Survive two GC pass)…
http://csharp.2000things.com/tag/garbage-collection

 

25. Thread Safe Collection classes?
ANS: System.Collections.Concurrent
1. ConcurrentDictionary<TKey, TValue>
2. ConcurrentStack<T>
3. ConcurrentQueue<T>
4. ConcurrentBag<T>
5. BlockingCollection<T>
http://msdn.microsoft.com/en-us/library/dd997369(v=vs.110).aspx
http://www.dotnetperls.com/concurrentdictionary

 

26. IDisposable?
ANS:
* IDisposable can be invoked “Deterministically”, and Garbage Collection invoke Destructor/Finalizer at in-deterministic time.
* “using” statement
http://www.codeproject.com/Articles/319826/IDisposable-Finalizer-and-SuppressFinalize-in-Csha
http://msdn.microsoft.com/en-us/library/ms244737.aspx

Dispose resources “Deterministically”:
a. Managed resources
b. unmanaged resources
By resources, we don’t just mean “Memory” – which too is important for example large Bitmap in memory. But “Resources” could be file handle, database connection… etc

* Note that Destructor/Finalizer not called if Dispose on the instance hasn’t been invoked
http://msdn.microsoft.com/en-us/library/system.idisposable.dispose.aspx

 

27. System.Windows.Forms.Timer vs System.Timers.Timer vs System.Threading.Timer?

ANS:

http://msdn.microsoft.com/en-us/magazine/cc164015.aspx
http://stackoverflow.com/questions/1435876/do-c-sharp-timers-elapse-on-a-separate-thread

 

28. When you abort a thread from Main, you get ThreadAbortException on Main? Or in Thread?
ANS: Thread’s catch statement, not Main where the thread was created/started

 

29. Why not Thread.Abort? “finally” block executed to release unmanaged resources?

ANS: “finally” block always executed on aborts, but
(a) You are not sure if any resources allocated BEFORE “try” block!
(b) Thread aborted when “finally” block executed half way?

Imagine your code open an Excel file, execute some VBA embedded on a thread. Then half way thru thread is aborted?

 

30. Examples of real world usage of annonymous types?

http://stackoverflow.com/questions/11795046/real-world-example-for-anonymous-types-of-c-sharp-net

ANS:
LINQ queries use them a lot:
var productQuery =
from prod in products
select new { prod.Color, prod.Price };
The { prod.Color, prod.Price } is an anonymous type that has a read-only Color and Price property. If you would iterate through the results of that query you could use that type as any other class:

foreach (var v in productQuery)
{
Console.WriteLine(“Color={0}, Price={1}”, v.Color, v.Price);
}
In other words, you didn’t have to define a new class that would look something like this:
public class ColoredPricedItem
{
public Color {get;}
public Price {get;}
}

 

31. Sealed vs private
private class A{}

private class B : A{}

sealed class C{}

// Error 1 ‘SimpleConsole.Test.D’: cannot derive from sealed type ‘SimpleConsole.Test.C’
class D : C{}

 

32. Memory limit?
Addressable Memory? 32bit vs 64bit? 32bit 2GB default, 64 bit 8TB. But you won’t have 8TB Physical Memory –> Paging
Single Object Limit? For both x86/x64, single object < 2GB
http://stackoverflow.com/questions/6107322/memory-limitations-in-a-64-bit-net-application
http://stackoverflow.com/questions/17808946/out-of-memory-exception-on-64bit
http://stackoverflow.com/questions/2399162/process-memory-limit-of-64-bit-process

 

33. Large Object Heap? No compacting – thus performance improvement
http://blogs.msdn.com/b/mariohewardt/archive/2013/06/26/no-more-memory-fragmentation-on-the-large-object-heap.aspx
http://stackoverflow.com/questions/8951836/why-large-object-heap-and-why-do-we-care

 

34. Dynamics vs Var
http://www.codeproject.com/Tips/460614/Difference-between-var-and-dynamic-in-Csharp
http://www.codeguru.com/csharp/article.php/c19053/Using-DynamicObject-and-ExpandoObject.htm

What’s the use of “dynamics”?
Example 1. Extending from “System.Dynamic.DynamicObject” in combination with “System.Xml.Linq.XElement”:
http://www.codeproject.com/Articles/436406/Power-of-Dynamic-Reading-XML-and-CSV-files-made-ea

dynamic customerOrderXmlReader = DynamicXmlStream.Load(new FileStream(“../../Input/CustomerOrder.xml”, FileMode.Open));
foreach (dynamic order in
(customerOrderXmlReader.Root.Orders.Order as DynamicXmlStream).AsDynamicEnumerable().Where(ord => ord.ShipInfo.ShipRegion.Value == “CA”))
{
Console.WriteLine(order.ToString());
Console.WriteLine(new string(‘-‘, 40));
}

Example 2. Invoke method via reflection vs
Reflection
object calc = GetCalculator();
Type calcType = calc.GetType();
object res = calcType.InvokeMember(
“Add”, BindingFlags.InvokeMethod,
null, new object[] { 10, 20 });
int sum = Convert.ToInt32(res);
Dynamics
dynamic calc = GetCalculator();
int sum = calc.Add(10, 20);

35. class vs struct?
ANS:
class: lock, as-operator, inheritance, null, destructor, field initialize
struct: sizeof, stackalloc, default constructor
differences: Equals, stack vs heap

http://www.jaggersoft.com/pubs/StructsVsClasses.htm

 

36. struct on heap or stack?
struct A {}
A a = new A(); –> On heap? Or stack?

ANS: stack

A lot of confusion has been wrought by people explaining the difference between value types and reference types as “value types go on the stack, reference types go on the heap”. This is simply untrue (as stated) and this article attempts to clarify matters somewhat.
http://yoda.arachsys.com/csharp/memory.html
http://www.codeproject.com/Articles/20620/Structs-in-C-Structs-vs-Classes-Heap-or-Stack-Stru

 

37. Stack vs Heap
* The stack is the memory set aside as scratch space for a thread of execution. When a function is called, a block is reserved on the top of the stack for local variables and some bookkeeping data. When that function returns, the block becomes unused and can be used the next time a function is called. The stack is always reserved in a LIFO order; the most recently reserved block is always the next block to be freed. This makes it really simple to keep track of the stack; freeing a block from the stack is nothing more than adjusting one pointer.
* The heap is memory set aside for dynamic allocation. Unlike the stack, there’s no enforced pattern to the allocation and deallocation of blocks from the heap; you can allocate a block at any time and free it at any time. This makes it much more complex to keep track of which parts of the heap are allocated or free at any given time; there are many custom heap allocators available to tune heap performance for different usage patterns.
http://stackoverflow.com/questions/79923/what-and-where-are-the-stack-and-heap

 

38. yield return
http://www.dotnetperls.com/yield

foreach (int value in ComputePower(2, 30))
{
Console.Write(value);
Console.Write(” “);
}

public static IEnumerable<int> ComputePower(int number, int exponent)
{
int exponentNum = 0;
int numberResult = 1;
//
// Continue loop until the exponent count is reached.
//
while (exponentNum < exponent)
{
//
// Multiply the result.
//
numberResult *= number;
exponentNum++;
//
// Return the result with yield.
//
yield return numberResult;
}
}

 

39. Predicate<T> vs FUNC<T,TRESULT>?
Predicate<T> is equivalent to FUNC<T,bool>

 

40. What code do you write to constrain a generic dictionary named MyDictionary to have value-type keys with reference type values?
public class MyDictionary<Tkey,TValue>:Dictionary<Tkey,TValue>
where Tkey:struct
where TValue:class
{

}
http://stackoverflow.com/questions/12773990/generic-dictionary-with-value-type-keys-and-reference-type-values

 

41. Initialize a list of string? Syntax?
IList<string> types = new List<string> { “a”, “b”, “c” };

 

42. What gets printed?
class Member
{
public int FreeTickets { get; set; }
}

class Associate : Member
{
public new int FreeTickets { get; set; } <– Note, “new” keyword hides the base class property
}

Associate a = new Associate();
Member b = a;
a.FreeTickets = 1;
b.FreeTickets = 2;
Console.WriteLine(a.FreeTickets); // 1
Console.WriteLine(b.FreeTickets); // 2

 

43. System.Windows.Forms.Timer vs System.Timers.Timer vs System.Threading.Timer
ANS:
System.Windows.Forms: UI thread
System.Timers: UI or worker
System.Threading: thread Worker thread

http://msdn.microsoft.com/en-us/magazine/cc164015.aspx

 

44. Given:
static void SomeOtherFunc(decimal a, decimal b)
{
double c = (double) a / (double) b;
Console.WriteLine(a);
Console.WriteLine(b);
Console.WriteLine(c);

return;
}

Which compiles? select multiples
(a) SomeOtherFunc(3.2m, 2.0);
(b) SomeOtherFunc(3.2m, 2); <– ok
(c) SomeOtherFunc(3.2m, 2m); <– ok
(d) SomeOtherFunc(3.2m, 2d);

http://www.dotnetperls.com/suffix

Continuing from (1), print statements gives if you call SomeOtherFunc(3.00m, 2)?
(a) 3000000, 2, 1.5
(b) 3.00, 2, 1.5 <– Correct
(c) 3, 2, 1.5
(d) 3, 2, 1.75 <– Note this is designed to filter those who’s genuinely retarded

Continuing from (2), print statements if SomeOtherFunc(3.00m, (decimal) 2.00)?
(a) 3000000, 2, 1.5
(b) 3.00, 2, 1.5 <– Correct
(c) 3, 2, 1.5
(d) 3, 2, 1.75

 

45. What’s HashCode? Hashcode vs Equals?

“A hash function is any algorithm that maps data of arbitrary length to data of a fixed length. The values returned by a hash function are called hash values, hash codes, hash sums, checksums or simply hashes. “

It’s perfectly possible for two different object meant to be unequal to have same HashCode!
But Equal should be overridden such that “Equal” object should have same HashCode.
http://en.wikipedia.org/wiki/Hash_function

If ObjA.HashCode==ObjB.HashCode Then ObjA May/MayNot Equals(ObjB)
i.e. Objects with the same hash code must be equal – WRONG!

If ObjA.NotEquals(ObjB), Then ObjA.HashCode May/MayNot != ObjA.HashCode
i.e. Unequal objects must have different hash codes – WRONG!

int x = 13;
int HashCode = x.GetHashCode();
Object o = new Object();
HashCode = o.GetHashCode();

 

46. What happen Dictionary HashCode collision? Affects only performance. If Equals correct, you’d still retrieve the correct object, just slower.
“Whenever two different object instances yield the same hash code, they are stored in the same internal bucket of the dictionary”

http://stackoverflow.com/questions/2240231/how-well-does-net-dictionary-resolve-collisions

int x = 13;
int y = 13;
HashSet<int> Map = new HashSet<int>();
Map.Add(x);
Map.Add(y); <– OK

Dictionary<int, string> Dict = new Dictionary<int, string>();
Dict.Add(x, “x”);
Dict.Add(y, “y”); <– Exception! You can have two keys with same Hashcode, but not duplicate keys!

Here’s another example,

class Entry
{
    public int Key { get; set; }
    public string Content { get; set; }

    public override int GetHashCode()
    {
        return 1; < Hardcoded to 1 so we have hash collision
    }
}

Entry Entry1 = new Entry() { Key = 1, Content = “xxx” };
Entry Entry2 = new Entry() { Key = 2, Content = “yyy” };
IDictionary<Entry, string> Entries = new Dictionary<Entry, string>();
Entries.Add(Entry1, “aaa”);
Entries.Add(Entry2, “bbb”); < This is OK, won’t throw any exception!
Console.WriteLine(“Entries count: ” + Entries.Count);

 

http://eclipsesource.com/blogs/2012/09/04/the-3-things-you-should-know-about-hashcode/

47. What happen if you forget implement GetHashCode?

Then Base class Object.GetHashCode()
“The GetHashCode method can be overridden by a derived type. If GetHashCode is not overridden, hash codes for reference types are computed by calling the Object.GetHashCode method of the base class, which computes a hash code based on an object’s reference”
http://msdn.microsoft.com/en-us/library/system.object.gethashcode.aspx

 

48. C# has pointers?

http://www.c-sharpcorner.com/UploadFile/rajeshvs/PointersInCSharp11112005051624AM/PointersInCSharp.aspx

int x = 100;
int *ptr = & x;

 

49. unsafe/fixed – What are they and when do we need them?
http://www.dotnetperls.com/fixed
http://www.dotnetperls.com/unsafe

unsafe // Also need Project build configuration to “Allow unsafe code”
{
int num = 12345;
int* ptr = &num;
Console.WriteLine(*ptr);
Console.WriteLine(ptr->ToString());
}

unsafe
{
string value = “ABCDE”;

/*
Objects in memory are moved at almost any time. This makes garbage collection possible. But when we use unsafe pointers to         memory addresses, that memory must not be moved. The fixed statement fixes memory in one location.
*/
fixed (char* pointer = value)
{
// Add one to each of the characters.
for (int i = 0; pointer[i] != ”; ++i)
{
Console.Write(pointer[i]);
pointer[i]++;
}
}
}

So, why pin/fix memory? For example copy a string into a byte[] – following method eliminate Intermediate variable of type byte[], and the resultant Garbage Collection – thus improvement in Performance (Fewer garbage collection).

http://stackoverflow.com/questions/21981132/whats-the-use-of-c-sharp-keyword-fixed-unsafe/21981333?noredirect=1#comment33311290_21981333
http://stackoverflow.com/questions/15307431/c-sharp-copy-variables-into-buffer-without-creating-garbage

FROM:
int variableToCopy = 9861;
byte[] buffer = new byte[1024];
byte[] bytes = BitConverter.GetBytes(variableToCopy); <– Conversion not necessary
Buffer.BlockCopy(bytes, 0, buffer, 0, 4); <– Replaced by directly referencing memory location: *(int*)pbuffer = v1;
float anotherVariableToCopy = 6743897.6377f;
bytes = BitConverter.GetBytes(anotherVariableToCopy);
Buffer.BlockCopy(bytes, 0, buffer, 4, sizeof(float));

TO – basically, you skipped call to Buffer.BlockCopy and Buffer.BlockCopy:
int v1 = 123;
float v2 = 253F;
byte[] buffer = new byte[1024];
fixed (byte* pbuffer = buffer)
{
//v1 is stored on the first 4 bytes of the buffer:
*(int*)pbuffer = v1;
pbuffer += 4; //4 bytes per int

//v2 is stored on the second 4 bytes of the buffer:
*(float*)pbuffer = v2;
}

50. Jagged array? What’s it?
ANS: http://www.dotnetperls.com/jagged-array

 

51. What are the different ways to parse and compose XML?

ANS

a. XmlReader – fast forward only, read only

b. XmlDocument – forward/backward, read+write

c. XPathDocument – forward/backward, read only

d. System.Xml.Linq – forward/backward, more terse syntax than (a)-(c)

e. DynamicXmlStream – most terse syntax among all, read only

XML/xpath/XSL
http://w3schools.com
http://www.indiabix.com/technical/dotnet/xml/

Example 1: XmlReader http://www.dotnetperls.com/xmlreader
using (FileStream fileSteam = File.OpenRead(fileName))
{
XmlReaderSettings settings;
settings = new XmlReaderSettings();
settings.ConformanceLevel = ConformanceLevel.Document;

using(XmlReader reader = XmlReader.Create(fileSteam, settings))
{
while (reader.Read())
{
// reader.Name|Value
}
}
}

Example 2: XmlDocument (Editable, forward/backward anything you like)
XmlDocument vs XPathDocument: http://msdn.microsoft.com/en-us/library/eh3exdc4(v=vs.110).aspx

XmlDocument xml = new XmlDocument();
xml.LoadXml(myXmlString); // suppose that myXmlString contains “<Names>…</Names>”

XmlNodeList xnList = xml.SelectNodes(“/Names/Name”); <– SelectNodes takes an XPath
foreach (XmlNode xn in xnList)
{
string firstName = xn[“FirstName”].InnerText;
string lastName = xn[“LastName”].InnerText;
Console.WriteLine(“Name: {0} {1}”, firstName, lastName);
}

Example 3: XPath (Read only, forward/backward anything you like)
XPathDocument xmlDoc = new XPathDocument(Rdr);
XPathNavigator Nav = xmlDoc.CreateNavigator();
XPathNodeIterator Iter = Nav.Select(“/SERIALIZER_ROOT/SERIALIZER_OBJECT”);
while (Iter.MoveNext())
{
// Iter.Current.Value|InnerText|InnerXml
// Iter.Current.GetAttribute($ATTRIBNAME$)
}

Example 4: System.Xml.Linq – http://www.dotnetcurry.com/showarticle.aspx?ID=564
strXml = System.IO.File.ReadAllText(“Sample.xml”);
var Customers = from Customer in System.Xml.Linq.XElement.Parse(strXml).Element(“Customers”).Elements(“Customer”)
where Customer.Element(“FullAddress”).Element(“Country”).Value == “Canada” || Customer.Attribute(“Country”).Value == “CA”
select Customer;
foreach (var Customer in Customers)
{
Console.WriteLine(Customer.ToString());
}

Example 5. Parse using DynamicXmlStream, derived from System.Dynamic.DynamicObject – http://www.codeproject.com/Articles/436406/Power-of-Dynamic-Reading-XML-and-CSV-files-made-ea
dynamic customerOrderXmlReader = DynamicXmlStream.Load(new FileStream(“../../Input/CustomerOrder.xml”, FileMode.Open));
Console.WriteLine(“First Customer’s Company Name = ” + customerOrderXmlReader.Root.Customers.Customer[0].CompanyName.Value);

Basically, “DynamicXmlStream” extends “System.Dynamic.DynamicObject”, you’d need override:
bool TryGetMember(GetMemberBinder binder, out object result)
bool TrySetMember(SetMemberBinder binder, object value)
bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result)
bool TrySetIndex(SetIndexBinder binder, object[] indexes, object value)
bool TryConvert(ConvertBinder binder, out object result)
bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)

 

52. What’s System.Collections.ObjectModel.ObservableCollection and INotifyPropertyChanged? When do we need them?

ANS
For example, if your WPF form binding to an observable collection, add/remove elements will cause WPF to rebind the list.
ObservableCollection<ConnectionConfiguration> ConnectionList

However, change to element within the collection will not propagate to user interface automatically, unless you implement INotifyPropertyChanged.

public class ConnectionConfiguration : System.ComponentModel.INotifyPropertyChanged, ICloneable
{
public event PropertyChangedEventHandler PropertyChanged;

private void NotifyPropertyChanged(String Info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(Info));
}
}

public string ConnectionName
{
get { return _ConnectionName; }
set {
_ConnectionName = value;
NotifyPropertyChanged(“ConnectionName”);
}
}

}

REF:

http://stackoverflow.com/questions/1427471/observablecollection-not-noticing-when-item-in-it-changes-even-with-inotifyprop/14919127#14919127
http://www.codeproject.com/KB/WPF/BeginWPF5.aspx
http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx

 

53. Is DTC (Distributed Transaction Coordinator) a requirement for TransactionScope to work?
“TransactionScope uses the LTM – Lightweight Transaction Manager in .Net. Only if you open connections against more than one database should TransactionScope promote the transaction to the 2PC-based TX-manager, DTC.”
http://stackoverflow.com/questions/11243855/transactionscope-alternative-without-dtc

 

54. Race condition (volatile) vs Deadlocks –
“The volatile keyword indicates that a field might be modified by multiple threads that are executing at the same time. Fields that are declared volatile are not subject to compiler optimizations that assume access by a single thread. This ensures that the most up-to-date value is present in the field at all times.
The volatile modifier is usually used for a field that is accessed by multiple threads without using the lock statement to serialize access.”

http://igoro.com/archive/volatile-keyword-in-c-memory-model-explained/
http://msdn.microsoft.com/en-us/library/x13ttww7.aspx

 

55. How do different threads talks to each other and to main thread?

a. Among workers threads?

* Context object? AppDomain.CurrentDomain.Get/SetData

* Shared thread start arguments

b. Between UI thread and workers thread?

* System.ComponentModel.BackgroundWorker Class

* WPF dispatcher object?

Dispatcher.Invoke(
System.Windows.Threading.DispatcherPriority.Normal,
new Action(
delegate()
{

}
));

 

56. TCP vs UDP?

ANS:

TCP Connection Oriented, from one IP to another IP. Examples, HTTP, HTTPs, FTP, SMTP, Telnet

UDP connection-less, stateless. Examples, DNS, DHCP, TFTP, SNMP, RIP, VOIP.

REF:

http://www.diffen.com/difference/TCP_vs_UDP

TcpListener-TcpClient/UdpListener-UdpClient
http://www.jarloo.com/c-udp-multicasting-tutorial/

 

57.  Annonymous Types and Edge Cases – Which line will cause compile error? ANS: Highlighted red

var point = new { X = 13, Y = 7 };
var point2 = new { X = 3, Y = 4 };
var point3 = new { X = 3.1, Y = 4 };
var point4 = new { Y = 4, X = 3 };
// var point5 = new { X = null }; // compile error, initializer cannot be null

// point = 1; // Compile error, point already been assigned to an annonymous type. You can’t assign to it anything of different type.
point = point2; // This is fine
// point = point3; // point3 is off different annonymous type as X = double, thus again compile error
// point = point4; // point4 also considered a different annonymous type as X/Y order swapped, thus compile error

dynamic x = 2.3;
x = “Some other shit”;

REF: http://geekswithblogs.net/BlackRabbitCoder/archive/2012/06/21/c.net-little-wonders-the-joy-of-anonymous-types.aspx

 

58. Named methods, Anonymous Delegate/Method vs Lambda expression?

ANS:

Old days: Named Delegate
public delegate int FoldIntDelegate(int a, int b);

public int Fold(FoldIntDelegate fid, params int[] list)
{
int result = 1;
foreach (int i in list)
result = fid(result, i);
return result;
}

int val = Fold(new FoldIntDelegate(delegate(int a, int b) { return a * b; }), 1, 3, 5, 7, 9);

.NET 2 Anonymous Delegate
int val = Fold(delegate(int a, int b) { return a * b; }, 1, 3, 5, 7, 9);

.NET 3 Lambda expression
int val = Fold((a, b) => a * b, 1, 3, 5, 7, 9);

REF

http://www.switchonthecode.com/tutorials/csharp-tutorial-the-lambda-operator

http://en.csharp-online.net/CSharp_Enhancements_for_LINQ%E2%80%94Use_Lambda_Expressions

 

59. Memory limit? Addressable Memory? 32bit vs 64bit?

ANS:

a. Addressable Memory: 32bit 2GB default, 64 bit 8TB.

b. Physical Memory: You won’t have 8TB Physical Memory. As soon as your application consumes more than available physical memory, Paging occurs and system slow significantly. Check with permon, “Avg Disk Queue length”, it should be a number smaller than 2.

c. Single Object Limit? For both x86/x64, single object < 2GB
http://stackoverflow.com/questions/6107322/memory-limitations-in-a-64-bit-net-application
http://stackoverflow.com/questions/17808946/out-of-memory-exception-on-64bit
http://stackoverflow.com/questions/2399162/process-memory-limit-of-64-bit-process

Large Object Heap? No compacting
http://blogs.msdn.com/b/mariohewardt/archive/2013/06/26/no-more-memory-fragmentation-on-the-large-object-heap.aspx
http://stackoverflow.com/questions/8951836/why-large-object-heap-and-why-do-we-care

 

60. Stack size has limit?

ANS:

Yes if exceeded, you get a StackOverflowException.  The default stack size for a .NET application is 1 MB (default is 256 KB for 32-bit ASP.NET apps and 512 KB for 64-bit ASP.NET apps)
http://stackoverflow.com/questions/823724/stack-capacity-in-c-sharp
http://www.atalasoft.com/cs/blogs/rickm/archive/2008/04/22/increasing-the-size-of-your-stack-net-memory-management-part-3.aspx

 

61. Dynamics vs Var?

ANS:
“var”: “Implicity type”. “var” is resolved at the compile time, and has Intellisense support.
“dynamic”: When you define a variable of type dynamic, compiler internally performs two steps. The first thing compiler does is, it converts the type to System.Object and then it postpones all the type validation to the runtime. Also, “dynamic” has Intellisense support.
http://www.codeproject.com/Articles/661824/Dynamic-vs-Var-vs-Object

 

62. Polymorphism – What’s “vtable” and how’s it work?

ANS: All instances of that class shares one vtable
http://www.programmerinterview.com/index.php/c-cplusplus/how-vtables-work/

 

63. What’s Reflection and how does it work?

ANS: Quote article by  hosted on Codeproject,  “Reflection is the ability of a managed code to read its own metadata for the purpose of finding assemblies, modules and type information at runtime. The classes that give access to the metadata of a running program are inSystem.ReflectionSystem.Reflection namespace defines the following types to analyze the module’s metadata of an assembly:AssemblyModuleEnumParameterInfoMemberInfoTypeMethodInfoConstructorInfoFieldInfo,EventInfo, and PropertyInfo. Whenever a .NET project is built, the code will be get complied into Intermediate language and then packaged in assembly. An assembly contains metadata which has the information about the type of classes defined meaning it contains all the required information about the members, fields, constructors, properties, methods, function, etc. used in the class for building the package.”

http://www.codeproject.com/Tips/791017/Reflection-Concept-and-Late-Binding-in-Csharp

 

64. How do you monitor  a process thread counts and memory consumption?

ANS:

Memory
Process currentProcess =System.Diagnostics.Process.GetCurrentProcess();long totalBytesOfMemoryUsed = currentProcess.WorkingSet64;

(This, however, doesn’t give you allocation in Gen 0/1/2 and LOH)

Thread Count
Process[] proc = Process.GetProcessesByName(“youprocess”);
Console.WriteLine(proc[0].Threads.Count.ToString());

http://stackoverflow.com/questions/1345797/how-to-get-how-many-threads-are-running-in-multithreaded-windows-service-applica
http://stackoverflow.com/questions/2342023/how-to-measure-the-total-memory-consumption-of-the-current-process-programatical
http://stackoverflow.com/questions/9349219/how-to-get-the-heap-memory-allocated-to-each-generation-gen0-gen1-gen2

 

65. Optimistic vs Pessemistic locking?

ANS: http://stackoverflow.com/questions/129329/optimistic-vs-pessimistic-locking

 

Not having enough of this? Here’s another list which I find useful: http://www.hanselman.com/blog/WhatGreatNETDevelopersOughtToKnowMoreNETInterviewQuestions.aspx

WPF Logical vs Visual Tree, in Plain English

There’re many discussions and articles on this subject – What I’m trying to do here is to deliver the explanation more Concisely and Intuitively.

1.Visual and Logical Tree serves different purposes.
With JQuery you can navigate up/down DOM tree in HTML. With WPF, it’s similar. Every WPF application has one Visual Tree, and one/more Logical Tree. You can navigate up/down XAML via Visual/LogicalTreeHelper – http://borsukmsdcrm.blogspot.hk/2011/04/wpf-visualtreehelper-findchild.html

The Logical Tree
The logical tree describes the relations between elements of the user interface. The logical tree is responsible for:
Inherit DependencyProperty values
Looking up element names for bindings
Forwarding RoutedEvents
Resolving DynamicResources references
The Visual Tree
The visual tree contains all logical elements including all visual elements of the template of each element. The visual tree is responsible for:
Rendering visual elements
Do Hit-Testing
Propagate Layout- and RenderTransforms
Propagate element Opacity
Propagate the IsEnabled property.
RelativeSource (FindAncestor)

And when will you need Visual/LogicalTreeHelper? For example, you have a grid of rows, user check a checkbox in one row. From code behind, you execute some business logic – and based on this logic, you set Visibility of another parent/child element in the same row. Of course, you can also do by way of Data Binding – really depends on which is easier, and which gives cleaner code.

 

2. Visual Tree as Elaboration/Extension of Logical Tree.
For example, http://tutorials.csharp-online.net/WPF_Concepts%E2%80%94Logical_and_Visual_Trees
Say for example, you navigate down from root Window, down the branch to some container (DockPanel, StackPanel, Grid, Canvas…etc), down to label.
With Logical Tree, “Label” element contains “string”.
With Visual Tree, “Label” element contains “Border”, then “ContentPresenter”, then “TextBlock”.

 

3. Logical Island? Why one WPF application has one Visual Tree and one/more Logical Tree?
Adding to complexity, when you navigate down from Window to branch, down to some container (DockPanel, StackPanel, Grid, Canvas…etc), Logical Tree stops when it hits anything that doesn’t derive from Visual/FrameworkElement.
For example, a Grid, contains a FlowDocument (derived from ContentElement). Further assume you have If you a ComboBox nested inside this FlowDocument.
With LogicalTree, you can navigate down from Window, to the Grid, and stops as you hit the FlowDocument. This FlowDocument however, contains a ComboBox – starts of another, separate, Logical Tree.
With VisualTree on the other hand, you can starts from Windows node, and continue all the way to the bottom.

Example:

<Window>
<Grid>
<ToggleButton TextElement.FontSize=”10″ Margin=”45,96,60,95″>
<FlowDocument> (First Logical Tree starts from Window tag, and stops here)
<Paragraph>
<Run Typography.Variants=”Superscript”>This text is Superscripted.</Run> This text isn’t.

</Paragraph>
<Paragraph>
<ComboBox Width=”125″ SelectedValue=”A”> (Start of another/separate Logical Tree)
<ComboBoxItem>A</ComboBoxItem>
<ComboBoxItem>B</ComboBoxItem>
<ComboBoxItem>C</ComboBoxItem>
</ComboBox>
</Paragraph>
</FlowDocument>
</ToggleButton>
</Grid>

</Window>

 

References
http://soumya.wordpress.com/2010/01/10/wpf-simplified-part-10-wpf-framework-class-hierarchy/
http://www.codeproject.com/Articles/21495/Understanding-the-Visual-Tree-and-Logical-Tree-in
WPF Inspector: http://wpfinspector.codeplex.com/

 

Simple Js to detect Credit Card type, and select CardType img accordingly

HTML

<img id=’MC’ src=’MC.png’ class=’cardimg’ /><img id=’VA’ src=’VA.png’ class=’cardimg’ /><img id=’DC’ src=’DC.png’ class=’cardimg’ /><img id=’JC’ src=’JC.png’ class=’cardimg’ /><img id=’AX’ src=’AX.png’ class=’cardimg’ />

<input type=’text’ id=’txtCardNumber’ onclick=’ShowHideCreditCardPanel2(this.value);’ />

 

Javascript (Uses JQuery to enumerate of list of card type images)

function selectCardImg(cardNumber)
{

         // STEP 1. detect card type
         var cardType = detectCreditCardType(cardNumber);

 

         // STEP 2. select appropriate card type image

$(‘.cardimg’).each(function (index, value) {
   var Id = $(this).attr(‘id’);
   $(this).removeClass(‘cardimg-selected’);
   if(Id==cardType)
      {
          $(this).addClass(‘cardimg-selected’);
      }
   }
)
}

function detectCreditCardType(cardNumber)
{
   var cardType = “”;

   if (/^5[1-5]\d{2}-?\d{4}-?\d{4}-?\d{4}$/.test(cardNumber))
   {
      cardType = “MC”;
   }
   else if (/^3[0,6,8]\d{12}$/.test(cardNumber))
   {
      cardType = “DC”;
   }
   else if (/^4\d{3}-?\d{4}-?\d{4}-?\d{4}$/.test(cardNumber))
   {
      cardType = “VA”;
   }
   else if (/(^(352)[8-9](\d{11}$|\d{12}$))|(^(35)[3-8](\d{12}$|\d{13}$))/.test(cardNumber))
   {
      cardType = “JC”;
   }
   else if (/^3[4,7]\d{13}$/.test(cardNumber))
   {
      cardType = “AX”;
   }

      return cardType ;
   }

 

Reference: http://blogs.markglibres.com/2010/10/c-get-credit-card-type.html

HTML Checkbox grouping

Simple code snippet – adapted from http://stackoverflow.com/questions/9709209/html-select-only-one-checkbox-in-a-group

<html>
<head>
<script src=”http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js”></script&gt;
<script type=”text/javascript”>
$(document).ready(function () {
$(“input:checkbox”).click(function() {
     if ($(this).is(“:checked”)) {
          var group = “input:checkbox[name='” + $(this).attr(“name”) + “‘]”;
          $(group).prop(“checked”, false);
          $(this).prop(“checked”, true);
     } else {
          $(this).prop(“checked”, false);
     }
     });
});
</script>
</head>
<body>
<form>
     <input type=”checkbox” class=”radio” value=”Red” name=”group1” />
     <input type=”checkbox” class=”radio” value=”Blue” name=”group1″ />
     <input type=”checkbox” class=”radio” value=”Yellow” name=”group1″ />
     <p>&nbsp;</p>
     <input type=”checkbox” class=”radio” value=”Dog” name=”group2” />
     <input type=”checkbox” class=”radio” value=”Cat” name=”group2″ />
     <input type=”checkbox” class=”radio” value=”Bird” name=”group2″ />
</form>
</body>
</html>