Thursday, May 31, 2007

MS SQL Server interview questions

  1. What is normalization? - Well a relational database is basically composed of tables that contain related data. So the Process of organizing this data into tables is actually referred to as normalization.
  2. What is a Stored Procedure? - Its nothing but a set of T-SQL statements combined to perform a single task of several tasks. Its basically like a Macro so when you invoke the Stored procedure, you actually run a set of statements.
  3. Can you give an example of Stored Procedure? - sp_helpdb , sp_who2, sp_renamedb are a set of system defined stored procedures. We can also have user defined stored procedures which can be called in similar way.
  4. What is a trigger? - Triggers are basically used to implement business rules. Triggers is also similar to stored procedures. The difference is that it can be activated when data is added or edited or deleted from a table in a database.
  5. What is a view? - If we have several tables in a db and we want to view only specific columns from specific tables we can go for views. It would also suffice the needs of security some times allowing specfic users to see only specific columns based on the permission that we can configure on the view. Views also reduce the effort that is required for writing queries to access specific columns every time.
  6. What is an Index? - When queries are run against a db, an index on that db basically helps in the way the data is sorted to process the query for faster and data retrievals are much faster when we have an index.
  7. What are the types of indexes available with SQL Server? - There are basically two types of indexes that we use with the SQL Server. Clustered and the Non-Clustered.
  8. What is the basic difference between clustered and a non-clustered index? - 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.
  9. What are cursors? - Well cursors help us to do an operation on a set of data that we retreive by commands such as Select columns from table. For example : If we have duplicate records in a table we can remove it by declaring a cursor which would check the records during retreival one by one and remove rows which have duplicate values.
  10. When do we use the UPDATE_STATISTICS command? - This command is basically used when we do a large processing of data. If we do a large amount of deletions any modification or Bulk Copy into the tables, we need to basically update the indexes to take these changes into account. UPDATE_STATISTICS updates the indexes on these tables accordingly.
  11. Which TCP/IP port does SQL Server run on? - SQL Server runs on port 1433 but we can also change it for better security.
  12. From where can you change the default port? - From the Network Utility TCP/IP properties –> Port number.both on client and the server.
  13. Can you tell me the difference between DELETE & TRUNCATE commands? - Delete command removes the rows from a table based on the condition that we provide with a WHERE clause. Truncate will actually remove all the rows from a table and there will be no data in the table after we run the truncate command.
  14. Can we use Truncate command on a table which is referenced by FOREIGN KEY? - No. We cannot use Truncate command on a table with Foreign Key because of referential integrity.
  15. What is the use of DBCC commands? - DBCC stands for database consistency checker. We use these commands to check the consistency of the databases, i.e., maintenance, validation task and status checks.
  16. Can you give me some DBCC command options?(Database consistency check) - DBCC CHECKDB - Ensures that tables in the db and the indexes are correctly linked.and DBCC CHECKALLOC - To check that all pages in a db are correctly allocated. DBCC SQLPERF - It gives report on current usage of transaction log in percentage. DBCC CHECKFILEGROUP - Checks all tables file group for any damage.
  17. What command do we use to rename a db? - sp_renamedb ‘oldname’ , ‘newname’
  18. Well sometimes sp_reanmedb may not work you know because if some one is using the db it will not accept this command so what do you think you can do in such cases? - In such cases we can first bring to db to single user using sp_dboptions and then we can rename that db and then we can rerun the sp_dboptions command to remove the single user mode.
  19. What is the difference between a HAVING CLAUSE and a WHERE CLAUSE? - Having Clause is basically used only with the GROUP BY function in a query. WHERE Clause is applied to each row before they are part of the GROUP BY function in a query.
  20. What do you mean by COLLATION? - Collation is basically the sort order. There are three types of sort order Dictionary case sensitive, Dictonary - case insensitive and Binary.
  21. What is a Join in SQL Server? - Join actually puts data from two or more tables into a single result set.
  22. Can you explain the types of Joins that we can have with Sql Server? - There are three types of joins: Inner Join, Outer Join, Cross Join
  23. When do you use SQL Profiler? - SQL Profiler utility allows us to basically track connections to the SQL Server and also determine activities such as which SQL Scripts are running, failed jobs etc..
  24. What is a Linked Server? - Linked Servers is a concept in SQL Server by which we can add other SQL Server to a Group and query both the SQL Server dbs using T-SQL Statements.
  25. Can you link only other SQL Servers or any database servers such as Oracle? - We can link any server provided we have the OLE-DB provider from Microsoft to allow a link. For Oracle we have a OLE-DB provider for oracle that microsoft provides to add it as a linked server to the sql server group.
  26. Which stored procedure will you be running to add a linked server? - sp_addlinkedserver, sp_addlinkedsrvlogin
  27. What are the OS services that the SQL Server installation adds? - MS SQL SERVER SERVICE, SQL AGENT SERVICE, DTC (Distribution transac co-ordinator)
  28. Can you explain the role of each service? - SQL SERVER - is for running the databases SQL AGENT - is for automation such as Jobs, DB Maintanance, Backups DTC - Is for linking and connecting to other SQL Servers
  29. How do you troubleshoot SQL Server if its running very slow? - First check the processor and memory usage to see that processor is not above 80% utilization and memory not above 40-45% utilization then check the disk utilization using Performance Monitor, Secondly, use SQL Profiler to check for the users and current SQL activities and jobs running which might be a problem. Third would be to run UPDATE_STATISTICS command to update the indexes
  30. Lets say due to N/W or Security issues client is not able to connect to server or vice versa. How do you troubleshoot? - First I will look to ensure that port settings are proper on server and client Network utility for connections. ODBC is properly configured at client end for connection ——Makepipe & readpipe are utilities to check for connection. Makepipe is run on Server and readpipe on client to check for any connection issues.
  31. What are the authentication modes in SQL Server? - Windows mode and mixed mode (SQL & Windows).
  32. Where do you think the users names and passwords will be stored in sql server? - They get stored in master db in the sysxlogins table.
  33. What is log shipping? Can we do logshipping with SQL Server 7.0 - Logshipping is a new feature of SQL Server 2000. We should have two SQL Server - Enterprise Editions. From Enterprise Manager we can configure the logshipping. In logshipping the transactional log file from one server is automatically updated into the backup database on the other server. If one server fails, the other server will have the same db and we can use this as the DR (disaster recovery) plan.
  34. Let us say the SQL Server crashed and you are rebuilding the databases including the master database what procedure to you follow? - For restoring the master db we have to stop the SQL Server first and then from command line we can type SQLSERVER –m which will basically bring it into the maintenance mode after which we can restore the master db.
  35. Let us say master db itself has no backup. Now you have to rebuild the db so what kind of action do you take? - (I am not sure- but I think we have a command to do it).
  36. What is BCP? When do we use it? - BulkCopy is a tool used to copy huge amount of data from tables and views. But it won’t copy the structures of the same.
  37. What should we do to copy the tables, schema and views from one SQL Server to another? - We have to write some DTS packages for it.
  38. What are the different types of joins and what dies each do?
  39. What are the four main query statements?
  40. What is a sub-query? When would you use one?
  41. What is a NOLOCK?
  42. What are three SQL keywords used to change or set someone’s permissions?
  43. What is the difference between HAVING clause and the WHERE clause?
  44. What is referential integrity? What are the advantages of it?
  45. What is database normalization?
  46. Which command using Query Analyzer will give you the version of SQL server and operating system?
  47. Using query analyzer, name 3 ways you can get an accurate count of the number of records in a table?
  48. What is the purpose of using COLLATE in a query?
  49. What is a trigger?
  50. What is one of the first things you would do to increase performance of a query? For example, a boss tells you that “a query that ran yesterday took 30 seconds, but today it takes 6 minutes”
  51. What is an execution plan? When would you use it? How would you view the execution plan?
  52. What is the STUFF function and how does it differ from the REPLACE function?
  53. What does it mean to have quoted_identifier on? What are the implications of having it off?
  54. What are the different types of replication? How are they used?
  55. What is the difference between a local and a global variable?
  56. What is the difference between a Local temporary table and a Global temporary table? How is each one used?
  57. What are cursors? Name four types of cursors and when each one would be applied?
  58. What is the purpose of UPDATE STATISTICS?
  59. How do you use DBCC statements to monitor various aspects of a SQL server installation?
  60. How do you load large data to the SQL server database?
  61. How do you check the performance of a query and how do you optimize it?
  62. How do SQL server 2000 and XML linked? Can XML be used to access data?
  63. What is SQL server agent?
  64. What is referential integrity and how is it achieved?
  65. What is indexing?
  66. What is normalization and what are the different forms of normalizations?
  67. Difference between server.transfer and server.execute method?
  68. What id de-normalization and when do you do it?
  69. What is better - 2nd Normal form or 3rd normal form? Why?
  70. Can we rewrite subqueries into simple select statements or with joins? Example?
  71. What is a function? Give some example?
  72. What is a stored procedure?
  73. Difference between Function and Procedure-in general?
  74. Difference between Function and Stored Procedure?
  75. Can a stored procedure call another stored procedure. If yes what level and can it be controlled?
  76. Can a stored procedure call itself(recursive). If yes what level and can it be controlled.?
  77. How do you find the number of rows in a table?
  78. Difference between Cluster and Non-cluster index?
  79. What is a table called, if it does not have neither Cluster nor Non-cluster Index?
  80. Explain DBMS, RDBMS?
  81. Explain basic SQL queries with SELECT from where Order By, Group By-Having?
  82. Explain the basic concepts of SQL server architecture?
  83. Explain couple pf features of SQL server
  84. Scalability, Availability, Integration with internet, etc.)?
  85. Explain fundamentals of Data ware housing & OLAP?
  86. Explain the new features of SQL server 2000?
  87. How do we upgrade from SQL Server 6.5 to 7.0 and 7.0 to 2000?
  88. What is data integrity? Explain constraints?
  89. Explain some DBCC commands?
  90. Explain sp_configure commands, set commands?
  91. Explain what are db_options used for?
  92. What is the basic functions for master, msdb, tempdb databases?
  93. What is a job?
  94. What are tasks?
  95. What are primary keys and foreign keys?
  96. How would you Update the rows which are divisible by 10, given a set of numbers in column?
  97. If a stored procedure is taking a table data type, how it looks?
  98. How m-m relationships are implemented?
  99. How do you know which index a table is using?
  100. How will oyu test the stored procedure taking two parameters namely first name and last name returning full name?
  101. How do you find the error, how can you know the number of rows effected by last SQL statement?
  102. How can you get @@error and @@rowcount at the same time?
  103. What are sub-queries? Give example? In which case sub-queries are not feasible?
  104. What are the type of joins? When do we use Outer and Self joins?
  105. Which virtual table does a trigger use?
  106. How do you measure the performance of a stored procedure?
  107. Questions regarding Raiseerror?
  108. Questions on identity?
  109. If there is failure during updation of certain rows, what will be the state?
Reference : http://www.techinterviews.com

Monday, May 14, 2007

Y Strings are immutable

This code illustrates how changing a property of an object using a particular reference to it is reflected in all other references to it. Note, however, that although strings are reference types, they work rather more like value types. When one string is set to the value of another, eg

string s1 = "hello";
string s2 = s1;
Then s2 does at this point reference the same string object as s1. However, when the value of s1 is changed, for instance with

s1 = "goodbye";
what happens is that a new string object is created for s1 to point to. Hence, following this piece of code, s1 equals "goodbye", whereas s2 still equals "hello".

The reason for this behaviour is that string objects are 'immutable'. That is, the properties of these objects can't themselves change. So in order to change what a string variable references, a new string object must be created.

C# Terminology

access modifier

A keyword, such as private, protected, internal, or public, that restricts access to a type or type member. For more information, see Access Modifiers.

accessible member

A member that can be accessed by a given type. An accessible member for one type is not necessarily accessible to another type. For more information, see Access Modifiers and Friend Assemblies.

accessor

A method that sets or retrieves the value of a private data member value that is associated with a property. Read-write properties have get and set accessors. Properties that are read-only have only a get accessor. For more information, see Properties.

anonymous method

An anonymous method is a code block that is passed as a parameter to a delegate. For more information, see Anonymous Methods.

base class

A class that is inherited by another 'derived' class. For more information, see Inheritance.

call stack

The series of method calls leading from the beginning of the program to the statement currently being executed at run time.

class

A data type that describes an object. Classes contain both data, and the methods for acting on the data. For more information, see Classes.

constructor

A special method on a class or struct that initializes the objects of that type. For more information, see Constructors.

delegate

A delegate is a type that references a method. Once a delegate is assigned a method, it behaves exactly like that method. For more information, see Delegates.

derived class

A class that uses inheritance to gain, augment, or modify the behavior and data of another 'base' class. For more information, see Inheritance.

destructor

A special method on a class or struct that prepares the instance for destruction by the system. For more information, see Destructors.

event

A member of a class or struct that sends notifications of a change. For more information, see Events.

field

A data member of a class or struct that is accessed directly.

generics

Generics allow you to define a class and or method that are defined with a type parameter. When client code instantiates the type, it specifies a particular type as an argument. For more information, see Generics.

IDE

Integrated Development Environment. The application that provides the unified user interface for the various development tools including the compiler, debugger, code editor, and designers.

immutable type

A type whose instance data, fields and properties, does not change after the instance is created. Most value types are immutable.

inaccessible member

A member that cannot be accessed by a given type. An inaccessible member for one type is not necessarily inaccessible to another type. For more information, see Access Modifiers.

inheritance

C# supports inheritance, so a class that derives from another class, known as the base class, inherits the same methods and properties. Inheritance involves base classes and derived classes. For more information, see Inheritance.

interface

A type that contains only the signatures of public methods, events, and delegates. An object that inherits the interface must implement all of the methods and events defined in the interface. Classes or structs may inherit any number of interfaces. For more information, see Interfaces

iterator

An iterator is a method that enables consumers of a class that contains a collection or array to use foreach, in (C# Reference) to iterate through that collection or array.

member

A field, property, method, or event declared on a class or struct.

method

A named code block that provides behavior for a class or struct.

mutable type

A type whose instance data, fields and properties, can be changed after the instance is created. Most Reference Types are mutable.

nested type

A type declared within the declaration of another type.

object

An instance of a class. An object exists in memory, and has data and methods that act on the data. For more information, see Objects, Classes, and Structs.

property

A data member accessed by means of an accessor. For more information, see Properties.

refactoring

Reusing previously entered code. The Visual C# Express Code Editor can intelligently reformat code to, for example, turn a block of highlight code into a method. For more information, see Refactoring.

reference type

A data type. A variable declared as a reference type point to a location where data is stored. For more information, see Reference Types.

static

A class or method declared as static exists without first being instantiated using the keyword new. Main() is a static method. For more information, see Static Classes and Static Class Members.

struct

A compound data type that is typically used to contain a few variables that have some logical relationship. Structs can also contain methods and events. Structs do not support inheritance but they do support interfaces. A struct is a value type, while a class is a reference type. For more information, see Structs.

value type

A value type is a data type that is allocated on the stack, as opposed to a reference type which is allocated on the heap. The built-In types, including the numeric types as well as the struct type and the nullable type, are all value types. The class type and string type are reference types. For more information, see Value Types (C# Reference).

Reference : http://msdn2.microsoft.com/en-us/library/ms173231(VS.80).aspx

DLL Hell 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.

"DLL Hell" refers to the set of problems caused when multiple applications attempt to share a common component like a dynamic link library (DLL) or a Component Object Model (COM) class. In the most typical case, one application will install a new version of the shared component that is not backward compatible with the version already on the machine. Although the application that has just been installed works well, existing applications that depended on a previous version of the shared component might no longer work. In some cases, the cause of the problem is even more subtle. In many cases there is a significant delay before a user discovers that an application has stopped working. As a result, it is often difficult to remember when a change was made to the machine that could have affected the application. A user may remember installing something a week ago, but there is no obvious correlation between that installation and the behavior they are now seeing. The reason for these issues is that version information about the different components of an application aren't recorded or enforced by the system. Also, changes made to the system on behalf of one application will typically affect all applications on the machine.

One reason why it was hard to build an isolated application was the run-time environment typically allowed the installation of only a single version of a component or an application. This restriction means that component authors must write their code in a way that remains backward compatible, otherwise they risk breaking existing applications when they install a new component. In practice, writing code that is forever backward compatible is extremely difficult, if not impossible. Also components were shared because disk space and memory was expensive. In the past few years, hard disk and memory prices have dropped dramatically, and disk space is no longer a premium. But as applications have increased in size and in modularity not so long ago many applications were entirely self-contained in a single .exe file - the DLL sharing issue has not been addressed, and the problem has grown over time.

.Net General Questions

  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.


  1. 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.
  2. 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%’.
  3. 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.
  4. What connections does Microsoft SQL Server support?
    Windows Authentication (via Active Directory) and SQL Server authentication (via Microsoft SQL Server username and password).
  5. 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.
  6. What does the Initial Catalog parameter define in the connection string?
    The database name to connect to.
  7. 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.
  8. 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.

Wednesday, May 9, 2007

Guid Structure

A GUID is a 128-bit integer (16 bytes) that can be used across all computers and networks wherever a unique identifier is required. Such an identifier has a very low probability of being duplicated.

Reference: http://msdn2.microsoft.com/en-us/library/system.guid.aspx

I/O in C#

Object
       |
        \----BinaryReader------\
        |                        |-->Binary IO used to read primitive data types(int,char..)    
        |----BinaryWriter------/
        |
        |
        |----Stream(Abstract)       ---> Byte Oriented IO   
        |       |
        |         \
        |         |-----FileStream
        |         |-----BufferedStream
        |         `-----MemoryStream
        |
        |
        |----TextReader(Abstract) ---> Character Based IO (For Reading....)
        |        |
        |         \
        |         |-----StreamReader
        |         `-----StringReader    
        |
        `----TextWriter(Abstract) ---> Character Based IO (For Writing....)
                |
                 \
                 |-----StreamWriter
                 `-----StringWriter     

Reference: http://www.csharphelp.com/archives4/archive673.html

Implementing the Singleton Pattern in C#

The singleton pattern is one of the best-known patterns in software engineering. Essentially, a singleton is a class which only allows a single instance of itself to be created, and usually gives simple access to that instance.

All these implementations share four common characteristics, however:

  • A single constructor, which is private and parameterless. This prevents other classes from instantiating it (which would be a violation of the pattern). Note that it also prevents subclassing - if a singleton can be subclassed once, it can be subclassed twice, and if each of those subclasses can create an instance, the pattern is violated. The factory pattern can be used if you need a single instance of a base type, but the exact type isn't known until runtime.
  • The class is sealed. This is unnecessary, strictly speaking, due to the above point, but may help the JIT to optimise things more.
  • A static variable which holds a reference to the single created instance, if any.
  • A public static means of getting the reference to the single created instance, creating one if necessary.

public sealed class Singleton
{
    static Singleton instance=null;
    static readonly object padlock = new object();
 
    Singleton()
    {
    }
 
    public static Singleton Instance
    {
        get
        {
            lock (padlock)
            {
                if (instance==null)
                {
                    instance = new Singleton();
                }
                return instance;
            }
        }
    }
}

This implementation is thread-safe. The thread takes out a lock on a shared object, and then checks whether or not the instance has been created before creating the instance. This takes care of the memory barrier issue (as locking makes sure that all reads occur logically after the lock acquire, and unlocking makes sure that all writes occur logically before the lock release) and ensures that only one thread will create an instance (as only

one thread can be in that part of the code at a time - by the time the second thread enters it,the first thread will have created the instance, so the expression will evaluate to false). Unfortunately, performance suffers as a lock is acquired every time the instance is requested.

Note that instead of locking on typeof(Singleton) as some versions of this implementation do, I lock on the value of a static variable which is private to the class. Locking on objects which other classes can access and lock on (such as the type) risks performance issues and even deadlocks. This is a general style preference of mine - wherever possible, only lock on objects specifically created for the purpose of locking, or which document that they are to be locked on for specific purposes (e.g. for waiting/pulsing a queue). Usually such objects should be private to the class they are used in. This helps to make writing thread-safe applications significantly easier.

Reference: http://www.csharphelp.com/archives4/archive670.html

Passing Value to a User Control from a Web Page and Loading User Control Dynamically

This article will give you a brief idea how to load a user control dynamically and pass values to it. This can be also taken as a best example for the use of properties.

Step1: Create a web page- default.aspx and place a place holder in it.

Step2: Create a user control- my.ascx and place a label in it.

Step3:In my.ascx.cs write the following code

public string prop //property

{

set { Label1.Text = value; } //write into property

}

Step4: Pace the following tag in default.aspx

<%@ Register Src="my.ascx" TagName="my" TagPrefix="uc1" %>

Step5: Place this code in default.aspx.cs

Protected void Page_Load(object sender, EventArgs e)

{

if (!Page.IsPostBack)

{

my uc = (my)Page.LoadControl("my.ascx" ); //loading the user control dynamically

uc.prop = "anoop"; //assign the label text a value

PlaceHolder1.Controls.Add(uc);

}

Tuesday, May 8, 2007

LDAP (Lightweight Directory Access Protocol)

The Lightweight Directory Access Protocol (LDAP) is a directory service protocol that runs on a layer above the TCP/IP stack. It provides a mechanism used to connect to, search, and modify Internet directories.

The LDAP directory service is based on a client-server model. The function of LDAP is to enable access to an existing directory.

The data model (data and namespace) of LDAP is similar to that of the X.500 OSI directory service, but with lower resource requirements. The associated LDAP API simplifies writing Internet directory service applications.

Reference: http://msdn2.microsoft.com/en-us/library/aa367008.aspx



ADSI (Active Directory Service Interfaces)

ADSI abstracts the functionality of different directory services from various network vendors into a single set of directory service interfaces for managing network resources. Administrators and developers can use ADSI to manage the directory service resources regardless of where on the network the resource is located. ADSI enables administrators to automate frequent tasks such as managing printers, managing users and groups, and setting network resource permissions. ADSI offers developers access to multiple directory service providers through a set of open interfaces. Using ADSI, applications are written to work with any directory service that offers an ADSI provider—Active Directory, LDAP, NDS, etc. The .NET managed version of ADSI is System.DirectoryServices

Reference: http://msdn2.microsoft.com/en-us/library/aa772170.aspx

WMI in .NET

WMI (Windows Management Instrumentation) is a component of the Microsoft operating system that allows you to monitor virtually every piece of the system (either locally or remotely) as well as control the windows operating system. This technology is particularly useful to professionals such as system administrators and database administrators who need to monitor and change client machines on a daily basis.

WMI is a powerful interface that can be used to monitor event logs, check disk space, or monitor peripherals. Through .NET, implementing WMI becomes a lot easier through Server Explorer Extensions and the System.Management and System.Management.Instrumentation interfaces. If you use WMI remotely, you may need to enable some security settings in the WMI properties window using the Computer Management Console. Have fun experimenting with WMI, another instrument at your disposal in .NET.


Reference:
http://www.c-sharpcorner.com/UploadFile/mgold/MonitoringRemoteLogusingWMI11232005020152AM/MonitoringRemoteLogusingWMI.aspx

What is a Bubble event?

The ASP.NET page framework provides a technique called event bubbling that allows a child control to propagate events up its containment hierarchy. Event bubbling enables events to be raised from a more convenient location in the controls hierarchy and allows event handlers to be attached to the original control as well as to the control that exposes the bubbled event.

Sometimes you need to handle one event on different layers of the class hierarchy. Take for example, the following case:

You need to implement a system which will receive data from the serial connection, parse it to single out several commands and handle them accordingly. The application will have to report its activity to a form. The form must present:

  1. a list of several connections
  2. the number of bytes sent and received for each connection
  3. last executed command for each connection

One of the possible approaches is:

  1. create a base class for low-level serial communication (Connection)
  2. create a class that will handle the commands and send the response back to the caller (Communicator)
  3. create a class that will contain several Communicators (CommManager)

You need to handle the following events:

  1. OnData

It is fired when data is sent or received to/from the serial port.

  1. OnCommand

It is fired when a command has been handled by the Communicator.

  1. OnError

If any errors occur in the data transmission, this event is fired by Connection.

Reference: http://msdn2.microsoft.com/en-us/library/aa719644(VS.71).aspx#Mtps_DropDownFilterText

http://www.codeproject.com/vb/net/BubbleEventsVB.asp

ASP.NET Master Pages

ASP.NET master pages allow you to create a consistent layout for the pages in your application. A single master page defines the look and feel and standard behavior that you want for all of the pages (or a group of pages) in your application. You can then create individual content pages that contain the content you want to display. When users request the content pages, they merge with the master page to produce output that combines the layout of the master page with the content from the content page.

Reference: http://www.codeproject.com/aspnet/masterpages.asp

Remoting in .NET

.NET Remoting provides a way for application in different machines/domains to communicate with each other. Remoting provides a powerful yet an easy way to communicate with object in different app domains. Any object which executes outside the app domain can be considered as Remote.

Remote objects are accessed via Channels, Channels can be thought of as Transport mechanism to pass messages to and from remote objects. All the method calls along with the parameters are passed to the remote object thru the channel viz. HTTP or TCP.

Step 1: Creating the Server Server.cs On Machine1

using System;
using System.IO;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels.HTTP;
namespace Server
{
public class ServiceClass : MarshalByRefObject
{
public void AddMessage (String msg)
{
Console.WriteLine (msg);
}
}
public class ServerClass
{
public static void Main ()
{
HTTPChannel c = new HTTPChannel (1095); ChannelServices.RegisterChannel (c);
RemotingServices.RegisterWellKnownType ("Server","Server.ServiceClass","ServiceClass",WellKnownObjectMode.Singleton);
Console.WriteLine ("Server ON at 1095");
Console.WriteLine ("Press enter to stop the server...");
Console.ReadLine ();
}
}
}

This will create a proxy called Server.dll which will be used to access the remote object

Client Code TheClient.cs

using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels.HTTP;
using Server;
public class TheClient
{
public static void Main (string[] args)
{
HTTPChannel c = new HTTPChannel (1077); ChannelServices.RegisterChannel (c);
ServiceClass sc = (ServiceClass) Activator.GetObject (typeof
(ServiceClass),http://:1095/ServiceClass);
sc.AddMessage ("Hello From Client");
}
}

Assembly in .Net

For the counterpart to assembly language in the Microsoft .NET framework, see Common Intermediate Language.

In the Microsoft .NET framework an assembly is a partially compiled code library for use in deployment, versioning and security. In the Microsoft Windows implementation of .NET, an assembly is a PE (portable executable) file. There are two types, process assemblies (EXE) and library assemblies (DLL).

This means that a library may have either .dll or .exe as its extension.

The code in an assembly is compiled into MSIL, which is then compiled into machine language at runtime by the CLR.

An assembly can consist of one or more files. Code files are called modules. An assembly can contain more than one code module and since it is possible to use different languages to create code modules this means that it is technically possible to use several different languages to create an assembly.

The name of an assembly consists of four parts:

  1. The short name. On Windows this is the name of the PE file without the extension.
  2. The culture. This is an RFC 1766 identifier of the locale for the assembly. In general, library and process assemblies should be culture neutral; the culture should only be used for satellite assemblies.
  3. The version. This is a dotted number made up for 4 values — major, minor, build and revision. The version is only used if the assembly has a strong name (see below).
  4. A public key token. This is a 64-bit hash of the public key which corresponds to the private key used to sign[1] the assembly. A signed assembly is said to have a strong name.