Toars I will smile to the world ^o^

11Nov/100

C# Questions and Answers – 07

  • Are private class-level variables inherited?
    Yes, but they are not accessible, so looking at it you can honestly say that they are not inherited. But they are.
  • Why does DllImport not work for me?
    All methods marked with the DllImport attribute must be marked as public static extern.
  • Why does my Windows application pop up a console window every time I run it?
    Make sure that the target type set in the project properties setting is set to Windows Application, and not Console Application. If you’re using the command line, compile with /target:winexe, not /target:exe.
  • Why do I get an error (CS1006) when trying to declare a method without specifying a return type?
    If you leave off the return type on a method declaration, the compiler thinks you are trying to declare a constructor. So if you are trying to declare a method that returns nothing, use void. The following is an example: // This results in a CS1006 error public static staticMethod (mainStatic obj) // This will work as wanted public static void staticMethod (mainStatic obj)
  • Why do I get a syntax error when trying to declare a variable called checked?
    The word checked is a keyword in C#.
  • Why do I get a security exception when I try to run my C# app?
    Some security exceptions are thrown if you are working on a network share. There are some parts of the frameworks that will not run if being run off a share (roaming profile, mapped drives, etc.). To see if this is what’s happening, just move the executable over to your local drive and see if it runs without the exceptions. One of the common exceptions thrown under these conditions is System.Security.SecurityException. To get around this, you can change your security policy for the intranet zone, code group 1.2, (the zone that running off shared folders falls into) by using the caspol.exe tool.
  • Why do I get a CS5001: does not have an entry point defined error when compiling?
    The most common problem is that you used a lowercase ‘m’ when defining the Main method. The correct way to implement the entry point is as follows: class test { static void Main(string[] args) {} }
  • What optimizations does the C# compiler perform when you use the /optimize+ compiler option?
    The following is a response from a developer on the C# compiler team: We get rid of unused locals (i.e., locals that are never read, even if assigned). We get rid of unreachable code. We get rid of try-catch with an empty try. We get rid of try-finally with an empty try. We get rid of try-finally with an empty finally. We optimize branches over branches: gotoif A, lab1 goto lab2: lab1: turns into: gotoif !A, lab2 lab1: We optimize branches to ret, branches to next instruction, and branches to branches.
  • What is the syntax for calling an overloaded constructor within a constructor (this() and constructorname() does not compile)?
    The syntax for calling another constructor is as follows:

    class B
    {
    	B(int i)
    	{
    	}
    } 
    
    class C : B
    {
    	C() : base(5) // call base constructor B(5)
    	{
    	} 
    
    	C(int i) : this() // call C()
    	{
    	} 
    
    	public static void Main()
    	{
    	}
    }
  • What is the equivalent to regsvr32 and regsvr32 /u a file in .NET development?
    Try using RegAsm.exe. Search MSDN on Assembly Registration Tool.
  • What is the difference between a struct and a class in C#?
    From language spec: The list of similarities between classes and structs is as follows. Longstructs can implement interfaces and can have the same kinds of members as classes. Structs differ from classes in several important ways; however, structs are value types rather than reference types, and inheritance is not supported for structs. Struct values are stored on the stack or in-line. Careful programmers can sometimes enhance performance through judicious use of structs. For example, the use of a struct rather than a class for a Point can make a large difference in the number of memory allocations performed at runtime. The program below creates and initializes an array of 100 points. With Point implemented as a class, 101 separate objects are instantiated-one for the array and one each for the 100 elements.
  • My switch statement works differently than in C++! Why?
    C# does not support an explicit fall through for case blocks. The following code is not legal and will not compile in C#:

    switch(x)
    {
    	case 0: // do something
    	case 1: // do something as continuation of case 0
    	default: // do something in common with
    		//0, 1 and everything else
    	break;
    }

    To achieve the same effect in C#, the code must be modified as shown below (notice how the control flows are explicit):

    class Test
    {
    	public static void Main() {
    		int x = 3;
    		switch(x)
    		{
    			case 0: // do something
    			goto case 1;
    			case 1: // do something in common with 0
    			goto default;
    			default: // do something in common with 0, 1, and anything else
    			break;
    		}
    	}
    }
  • Is there regular expression (regex) support available to C# developers?
    Yes. The .NET class libraries provide support for regular expressions. Look at the System.Text.RegularExpressions namespace.
  • Is there any sample C# code for simple threading?
    Yes:

    using System;
    using System.Threading;
    class ThreadTest
    {
    	public void runme()
    	{
    		Console.WriteLine("Runme Called");
    	}
    	public static void Main(String[] args)
    	{
    		ThreadTest b = new ThreadTest();
    		Thread t = new Thread(new ThreadStart(b.runme));
    		t.Start();
    	}
    }
  • Is there an equivalent of exit() for quitting a C# .NET application?
    Yes, you can use System.Environment.Exit(int exitCode) to exit the application or Application.Exit() if it’s a Windows Forms app.
  • Is there a way to force garbage collection?
    Yes. Set all references to null and then call System.GC.Collect(). If you need to have some objects destructed, and System.GC.Collect() doesn’t seem to be doing it for you, you can force finalizers to be run by setting all the references to the object to null and then calling System.GC.RunFinalizers().
  • Is there a way of specifying which block or loop to break out of when working with nested loops?
    The easiest way is to use goto:

    using System;
    class BreakExample
    {
    	public static void Main(String[] args) {
    		for(int i=0; i<3; i++)
    		{
    			Console.WriteLine("Pass {0}: ", i);
    			for( int j=0 ; j<100 ; j++ )
    			{
    				if ( j == 10)
    					goto done;
    				Console.WriteLine("{0} ", j);
    			}
    			Console.WriteLine("This will not print");
    		}
    		done:
    			Console.WriteLine("Loops complete.");
    	}
    }
  • Is it possible to restrict the scope of a field/method of a class to the classes in the same namespace?
    There is no way to restrict to a namespace. Namespaces are never units of protection. But if you’re using assemblies, you can use the ‘internal’ access modifier to restrict access to only within the assembly.
Filed under: .NET, C#, Interviews No Comments
11Nov/100

C# Questions and Answers – 06

  • Is it possible to inline assembly or IL in C# code?
    No.
  • Is it possible to have different access modifiers on the get/set methods of a property?
    No. The access modifier on a property applies to both its get and set accessors. What you need to do if you want them to be different is make the property read-only (by only providing a get accessor) and create a private/internal set method that is separate from the property.
  • Is it possible to have a static indexer in C#?
    No. Static indexers are not allowed in C#.
  • If I return out of a try/finally in C#, does the code in the finally-clause run?
    Yes. The code in the finally always runs. If you return out of the try block, or even if you do a “goto” out of the try, the finally block always runs:

    using System; 
    
    class main
    {
    	public static void Main()
    	{
    		try
    		{
    			Console.WriteLine("In Try block");
    			return;
    		}
    		finally
    		{
    			Console.WriteLine("In Finally block");
    		}
    	}
    }

    Both “In Try block” and “In Finally block” will be displayed. Whether the return is in the try block or after the try-finally block, performance is not affected either way. The compiler treats it as if the return were outside the try block anyway. If it’s a return without an expression (as it is above), the IL emitted is identical whether the return is inside or outside of the try. If the return has an expression, there’s an extra store/load of the value of the expression (since it has to be computed within the try block).

  • I was trying to use an “out int” parameter in one of my functions. How should I declare the variable that I am passing to it?
    You should declare the variable as an int, but when you pass it in you must specify it as ‘out’, like the following: int i; foo(out i); where foo is declared as follows: [return-type] foo(out int o) { }
  • How does one compare strings in C#?
    In the past, you had to call .ToString() on the strings when using the == or != operators to compare the strings’ values. That will still work, but the C# compiler now automatically compares the values instead of the references when the == or != operators are used on string types. If you actually do want to compare references, it can be done as follows: if ((object) str1 == (object) str2) { … } Here’s an example showing how string compares work:

    using System;
    public class StringTest
    {
    	public static void Main(string[] args)
    	{
    		Object nullObj = null; Object realObj = new StringTest();
    		int i = 10;
    		Console.WriteLine("Null Object is [" + nullObj + "]\n"
    			+ "Real Object is [" + realObj + "]\n"
    			+ "i is [" + i + "]\n");
    			// Show string equality operators
    		string str1 = "foo";
    		string str2 = "bar";
    		string str3 = "bar";
    		Console.WriteLine("{0} == {1} ? {2}", str1, str2, str1 == str2 );
    		Console.WriteLine("{0} == {1} ? {2}", str2, str3, str2 == str3 );
    	}
    }

    Output:

    Null Object is []
    Real Object is [StringTest]
    i is [10]
    foo == bar ? False
    bar == bar ? True
  • How do you specify a custom attribute for the entire assembly (rather than for a class)?
    Global attributes must appear after any top-level using clauses and before the first type or namespace declarations. An example of this is as follows:

    using System;
    [assembly : MyAttributeClass] class X {}

    Note that in an IDE-created project, by convention, these attributes are placed in AssemblyInfo.cs.

  • How do you mark a method obsolete?
    [Obsolete] public int Foo() {...}

    or

    [Obsolete("This is a message describing why this method is obsolete")] public int Foo() {...}

    Note: The O in Obsolete is always capitalized.

  • How do you implement thread synchronization (Object.Wait, Notify,and CriticalSection) in C#?
    You want the lock statement, which is the same as Monitor Enter/Exit:

    lock(obj) { // code }

    translates to

    try {
    	CriticalSection.Enter(obj);
    	// code
    }
    finally
    {
    	CriticalSection.Exit(obj);
    }
  • How do you directly call a native function exported from a DLL?
    Here’s a quick example of the DllImport attribute in action:

    using System.Runtime.InteropServices; \
    class C
    {
    	[DllImport("user32.dll")]
    	public static extern int MessageBoxA(int h, string m, string c, int type);
    	public static int Main()
    	{
    		return MessageBoxA(0, "Hello World!", "Caption", 0);
    	}
    }

    This example shows the minimum requirements for declaring a C# method that is implemented in a native DLL. The method C.MessageBoxA() is declared with the static and external modifiers, and has the DllImport attribute, which tells the compiler that the implementation comes from the user32.dll, using the default name of MessageBoxA. For more information, look at the Platform Invoke tutorial in the documentation.

  • How do I simulate optional parameters to COM calls?
    You must use the Missing class and pass Missing.Value (in System.Reflection) for any values that have optional parameters.
Filed under: .NET, C#, Interviews No Comments
11Nov/100

C# Questions and Answers – 05

Filed under: .NET, C#, Interviews No Comments
11Nov/100

C# Questions and Answers – 04

  • What do you know about .NET assemblies?
    Assemblies are the smallest units of versioning and deployment in the .NET application. Assemblies are also the building blocks for programs such as Web services, Windows services, serviced components, and .NET remoting applications.
  • What’s the difference between private and shared assembly?
    Private assembly is used inside an application only and does not have to be identified by a strong name. Shared assembly can be used by multiple applications and has to have a strong name.
  • What’s a strong name?
    A strong name includes the name of the assembly, version number, culture identity, and a public key token.
  • How can you tell the application to look for assemblies at the locations other than its own install?
    Use the directive in the XML .config file for a given application.

    <probing privatePath=”c:\mylibs; bin\debug” />

    should do the trick. Or you can add additional search paths in the Properties box of the deployed application.

  • How can you debug failed assembly binds?
    Use the Assembly Binding Log Viewer (fuslogvw.exe) to find out the paths searched.
  • Where are shared assemblies stored?
    Global assembly cache.
  • How can you create a strong name for a .NET assembly?
    With the help of Strong Name tool (sn.exe).
  • Where’s global assembly cache located on the system?
    Usually C:\winnt\assembly or C:\windows\assembly.
  • Can you have two files with the same file name in GAC?
    Yes, remember that GAC is a very special folder, and while normally you would not be able to place two files with the same name into a Windows folder, GAC differentiates by version number as well, so it’s possible for MyApp.dll and MyApp.dll to co-exist in GAC if the first one is version 1.0.0.0 and the second one is 1.1.0.0.
  • So let’s say I have an application that uses MyApp.dll assembly, version 1.0.0.0. There is a security bug in that assembly, and I publish the patch, issuing it under name MyApp.dll 1.1.0.0. How do I tell the client applications that are already installed to start using this new MyApp.dll?
    Use publisher policy. To configure a publisher policy, use the publisher policy configuration file, which uses a format similar app .config file. But unlike the app .config file, a publisher policy file needs to be compiled into an assembly and placed in the GAC.
  • What is delay signing?
    Delay signing allows you to place a shared assembly in the GAC by signing the assembly with just the public key. This allows the assembly to be signed with the private key at a later stage, when the development process is complete and the component or assembly is ready to be deployed. This process enables developers to work with shared assemblies as if they were strongly named, and it secures the private key of the signature from being accessed at different stages of development.
Filed under: .NET, C#, Interviews No Comments
11Nov/100

C# Questions and Answers – 03

  • Whats an assembly?
    Assemblies are the building blocks of .NET Framework applications; they form the fundamental unit of deployment, version control, reuse, activation scoping, and security permissions. An assembly is a collection of types and resources that are built to work together and form a logical unit of functionality. An assembly provides the common language runtime with the information it needs to be aware of type implementations. To the runtime, a type does not exist outside the context of an assembly.
  • Describe the difference between inline and code behind - which is best in a loosely coupled solution?
    ASP.NET supports two modes of page development: Page logic code that is written inside <script runat=server> blocks within an .aspx file and dynamically compiled the first time the page is requested on the server. Page logic code that is written within an external class that is compiled prior to deployment on a server and linked "behind" the .aspx file at run time.
  • Explain what a diffgram is, and a good use for one?
    A DiffGram is an XML format that is used to identify current and original versions of data elements. The DataSet uses the DiffGram format to load and persist its contents, and to serialize its contents for transport across a network connection. When a DataSet is written as a DiffGram, it populates the DiffGram with all the necessary information to accurately recreate the contents, though not the schema, of the DataSet, including column values from both the Original and Current row versions, row error information, and row order.
  • Where would you use an iHTTPModule, and what are the limitations of anyapproach you might take in implementing one?
    One of ASP.NET’s most useful features is the extensibility of the HTTP pipeline, the path that data takes between client and server. You can use them to extend your ASP.NET applications by adding pre- and post-processing to each HTTP request coming into your application. For example, if you wanted custom authentication facilities for your application, the best technique would be to intercept the request when it comes in and process the request in a custom HTTP module.
  • What are the disadvantages of viewstate/what are the benefits?
    No Answer Yet.
  • Describe session handling in a webfarm, how does it work and what are the limits?
    No Answer Yet.
  • How would you get ASP.NET running in Apache web servers - why would you even do this?
    No Answer Yet.
  • Whats MSIL, and why should my developers need an appreciation of it if at all?
    When compiling to managed code, the compiler translates your source code into Microsoft intermediate language (MSIL), which is a CPU-independent set of instructions that can be efficiently converted to native code. MSIL includes instructions for loading, storing, initializing, and calling methods on objects, as well as instructions for arithmetic and logical operations, control flow, direct memory access, exception handling, and other operations. Before code can be run, MSIL must be converted to CPU-specific code, usually by a just-in-time (JIT) compiler. Because the common language runtime supplies one or more JIT compilers for each computer architecture it supports, the same set of MSIL can be JIT-compiled and run on any supported architecture.
    When a compiler produces MSIL, it also produces metadata. Metadata describes the types in your code, including the definition of each type, the signatures of each type's members, the members that your code references, and other data that the runtime uses at execution time. The MSIL and metadata are contained in a portable executable (PE) file that is based on and extends the published Microsoft PE and common object file format (COFF) used historically for executable content. This file format, which accommodates MSIL or native code as well as metadata, enables the operating system to recognize common language runtime images. The presence of metadata in the file along with the MSIL enables your code to describe itself, which means that there is no need for type libraries or Interface Definition Language (IDL). The runtime locates and extracts the metadata from the file as needed during execution.
  • In what order do the events of an ASPX page execute. As a developer is it important to undertsand these events?
    Every Page object (which your .aspx page is) has nine events, most of which you will not have to worry about in your day to day dealings with ASP.NET. The three that you will deal with the most are: Page_Init, Page_Load, Page_PreRender.
  • Which method do you invoke on the DataAdapter control to load your generated dataset with data?

    System.Data.Common.DataAdapter.Fill(System.Data.DataSet);

    If my DataAdapter is sqlDataAdapter and my DataSet is dsUsers then it is called this way:

    sqlDataAdapter.Fill(dsUsers);

  • Which template must you provide, in order to display data in a Repeater control?
    ItemTemplate
  • How can you provide an alternating color scheme in a Repeater control?
    AlternatingItemTemplate Like the ItemTemplate element, but rendered for every other
    row (alternating items) in the Repeater control. You can specify a different appearance
    for the AlternatingItemTemplate element by setting its style properties.
  • What property must you set, and what method must you call in your code, in order to bind the data from some data source to the Repeater control?
    You must set the DataMember property which Gets or sets the specific table in the DataSource to bind to the control and the DataBind method to bind data from a source to a server control. This method is commonly used after retrieving a data set through a database query.
  • What base class do all Web Forms inherit from?
    System.Web.UI.Page
  • What method do you use to explicitly kill a user’s session?
    The Abandon method destroys all the objects stored in a Session object and releases their resources.
    If you do not call the Abandon method explicitly, the server destroys these objects when the session times out.

    Syntax: Session.Abandon

  • How do you turn off cookies for one page in your site?
    Use the Cookie.Discard Property which Gets or sets the discard flag set by the server. When true, this property instructs the client application not to save the Cookie on the user’s hard disk when a session ends.
  • Which two properties are on every validation control?
    ControlToValidate & ErrorMessage properties
  • What tags do you need to add within the asp:datagrid tags to bind columns manually?
    No Answer Yet.
  • How do you create a permanent cookie?
    Setting the Expires property to MinValue means that the Cookie never expires.
  • What tag do you use to add a hyperlink column to the DataGrid?
    No Answer Yet.
  • What is the standard you use to wrap up a call to a Web service?
    No Answer Yet.
  • Which method do you use to redirect the user to another page without performing a round trip to the client?
    Server.transfer()
  • What is the transport protocol you use to call a Web service?
    SOAP. Transport Protocols: It is essential for the acceptance of Web Services that they are based on established Internet infrastructure. This in fact imposes the usage of of the HTTP, SMTP and FTP protocols based on the TCP/IP family of transports. Messaging Protocol: The format of messages exchanged between Web Services clients and Web Services should be vendor neutral and should not carry details about the technology used to implement the service. Also, the message format should allow for extensions and different bindings to specific transport protocols. SOAP and ebXML Transport are specifications which fulfill these requirements. We expect that the W3C XML Protocol Working Group defines a successor standard.
  • True or False: A Web service can only be written in .NET.
    False.
  • What does WSDL stand for?
    Web Services Description Language
  • What property do you have to set to tell the grid which page to go to when using the Pager object?
    No Answer Yet.
  • What tags do you need to add within the asp:datagrid tags to bind columns manually?
    Column tag and an ASP:databound tag.
  • Which property on a Combo Box do you set with a column name, prior to setting the DataSource, to display data in the combo box?
  • How is a property designated as read-only?
    In VB.NET:

    Public ReadOnly Property PropertyName As ReturnType
    	Get 		 ‘Your Property Implementation goes in here
    	End Get
    End Property

    in C#

    public returntype PropertyName
    {
    	get{
    		//property implementation goes here
    	}
    	// Do not write the set implementation
    }
  • Which control would you use if you needed to make sure the values in two different controls matched?
    Use the CompareValidator control to compare the values of 2 different controls.
  • True or False: To test a Web service you must create a windows application or Web application to consume this service?
    False.
  • How many classes can a single .NET DLL contain?
    Unlimited.
Filed under: .NET, C#, Interviews No Comments
11Nov/100

C# Questions and Answers – 02

  • Explain the differences between Server-side and Client-side code?
    Server side scripting means that all the script will be executed by the server and interpreted as needed. ASP doesn’t have some of the functionality like sockets, uploading, etc. For these you have to make a custom components usually in VB or VC++. Client side scripting means that the script will be executed immediately in the browser such as form field validation, clock, email validation, etc. Client side scripting is usually done in VBScript or JavaScript. Download time, browser compatibility, and visible code - since JavaScript and VBScript code is included in the HTML page, then anyone can see the code by viewing the page source. Also a possible security hazards for the client computer.
  • What type of code (server or client) is found in a Code-Behind class?
    C#
  • Should validation (did the user enter a real date) occur server-side or client-side? Why?
    Client-side validation because there is no need to request a server side date when you could obtain a date from the client machine.
  • What does the "EnableViewState" property do? Why would I want it on or off?
    Enable ViewState turns on the automatic state management feature that enables server controls to re-populate their values on a round trip without requiring you to write any code. This feature is not free however, since the state of a control is passed to and from the server in a hidden form field. You should be aware of when ViewState is helping you and when it is not. For example, if you are binding a control to data on every round trip (as in the datagrid example in tip #4), then you do not need the control to maintain it’s view state, since you will wipe out any re-populated data in any case. ViewState is enabled for all server controls by default. To disable it, set the EnableViewState property of the control to false.
  • What is the difference between Server.Transfer and Response.Redirect? Why would I choose one over the other?
    Server.Transfer() : client is shown as it is on the requesting page only, but the all the content is of the requested page. Data can be persist across the pages using Context.Item collection, which is one of the best way to transfer data from one page to another keeping the page state alive. Response.Dedirect() :client know the physical loation (page name and query string as well). Context.Items loses the persisitance when nevigate to destination page. In earlier versions of IIS, if we wanted to send a user to a new Web page, the only option we had was Response.Redirect. While this method does accomplish our goal, it has several important drawbacks. The biggest problem is that this method causes each page to be treated as a separate transaction. Besides making it difficult to maintain your transactional integrity, Response.Redirect introduces some additional headaches. First, it prevents good encapsulation of code. Second, you lose access to all of the properties in the Request object. Sure, there are workarounds, but they’re difficult. Finally, Response.Redirect necessitates a round trip to the client, which, on high-volume sites, causes scalability problems. As you might suspect, Server.Transfer fixes all of these problems. It does this by performing the transfer on the server without requiring a roundtrip to the client.
  • Can you give an example of when it would be appropriate to use a web service as opposed to a non-serviced .NET component? When to Use Web Services:
    • Communicating through a Firewall When building a distributed application with 100s/1000s of users spread over multiple locations, there is always the problem of communicating between client and server because of firewalls and proxy servers. Exposing your middle tier components as Web Services and invoking the directly from a Windows UI is a very valid option.
    • Application Integration When integrating applications written in various languages and running on disparate systems. Or even applications running on the same platform that have been written by separate vendors.
    • Business-to-Business Integration This is an enabler for B2B intergtation which allows one to expose vital business processes to authorized supplier and customers. An example would be exposing electronic ordering and invoicing, allowing customers to send you purchase orders and suppliers to send you invoices electronically.
    • Software Reuse This takes place at multiple levels. Code Reuse at the Source code level or binary componet-based resuse. The limiting factor here is that you can reuse the code but not the data behind it. Webservice overcome this limitation. A scenario could be when you are building an app that aggregates the functionality of serveral other Applicatons. Each of these functions could be performed by individual apps, but there is value in perhaps combining the the multiple apps to present a unifiend view in a Portal or Intranet.
    • When not to use Web Services: Single machine Applicatons When the apps are running on the same machine and need to communicate with each other use a native API. You also have the options of using component technologies such as COM or .NET Componets as there is very little overhead.
    • Homogeneous Applications on a LAN If you have Win32 or Winforms apps that want to communicate to their server counterpart. It is much more efficient to use DCOM in the case of Win32 apps and .NET Remoting in the case of .NET Apps.
  • Let’s say I have an existing application written using Visual Studio (VBInterDevand this application utilizes WindowsCOM+ transaction services. How would you approach migrating this application to .NET?
    No Answer Yet.
  • Can you explain the difference between an ADO.NET Dataset and an ADO Recordset?
    • In ADO, the in-memory representation of data is the recordset. In ADO.NET, it is the dataset. There are important differences between them.
    • A recordset looks like a single table. If a recordset is to contain data from multiple database tables, it must use a JOIN query, which assembles the data from the various database tables into a single result table. In contrast, a dataset is a collection of one or more tables. The tables within a dataset are called data tables; specifically, they are DataTable objects. If a dataset contains data from multiple database tables, it will typically contain multiple DataTable objects. That is, each DataTable object typically corresponds to a single database table or view. In this way, a dataset can mimic the structure of the underlying database. A dataset usually also contains relationships. A relationship within a dataset is analogous to a foreign-key relationship in a database —that is, it associates rows of the tables with each other. For example, if a dataset contains a table about investors and another table about each investor’s stock purchases, it could also contain a relationship connecting each row of the investor table with the corresponding rows of the purchase table. Because the dataset can hold multiple, separate tables and maintain information about relationships between them, it can hold much richer data structures than a recordset, including self-relating tables and tables with many-to-many relationships.
    • In ADO you scan sequentially through the rows of the recordset using the ADO MoveNext method. In ADO.NET, rows are represented as collections, so you can loop through a table as you would through any collection, or access particular rows via ordinal or primary key index. DataRelation objects maintain information about master and detail records and provide a method that allows you to get records related to the one you are working with. For example, starting from the row of the Investor table for "Nate Sun," you can navigate to the set of rows of the Purchase table describing his purchases. A cursor is a database element that controls record navigation, the ability to update data, and the visibility of changes made to the database by other users. ADO.NET does not have an inherent cursor object, but instead includes data classes that provide the functionality of a traditional cursor. For example, the functionality of a forward-only, read-only cursor is available in the ADO.NET DataReader object. For more information about cursor functionality, see Data Access Technologies.
    • Minimized Open Connections: In ADO.NET you open connections only long enough to perform a database operation, such as a Select or Update. You can read rows into a dataset and then work with them without staying connected to the data source. In ADO the recordset can provide disconnected access, but ADO is designed primarily for connected access. There is one significant difference between disconnected processing in ADO and ADO.NET. In ADO you communicate with the database by making calls to an OLE DB provider. In ADO.NET you communicate with the database through a data adapter (an OleDbDataAdapter, SqlDataAdapter, OdbcDataAdapter, or OracleDataAdapter object), which makes calls to an OLE DB provider or the APIs provided by the underlying data source. The important difference is that in ADO.NET the data adapter allows you to control how the changes to the dataset are transmitted to the database — by optimizing for performance, performing data validation checks, or adding any other extra processing. Data adapters, data connections, data commands, and data readers are the components that make up a .NET Framework data provider. Microsoft and third-party providers can make available other .NET Framework data providers that can be integrated into Visual Studio.
    • Sharing Data Between Applications. Transmitting an ADO.NET dataset between applications is much easier than transmitting an ADO disconnected recordset. To transmit an ADO disconnected recordset from one component to another, you use COM marshalling. To transmit data in ADO.NET, you use a dataset, which can transmit an XML stream.
    • Richer data types.COM marshalling provides a limited set of data types — those defined by the COM standard. Because the transmission of datasets in ADO.NET is based on an XML format, there is no restriction on data types. Thus, the components sharing the dataset can use whatever rich set of data types they would ordinarily use.
    • Performance. Transmitting a large ADO recordset or a large ADO.NET dataset can consume network resources; as the amount of data grows, the stress placed on the network also rises. Both ADO and ADO.NET let you minimize which data is transmitted. But ADO.NET offers another performance advantage, in that ADO.NET does not require data-type conversions. ADO, which requires COM marshalling to transmit records sets among components, does require that ADO data types be converted to COM data types.
    • Penetrating Firewalls.A firewall can interfere with two components trying to transmit disconnected ADO recordsets. Remember, firewalls are typically configured to allow HTML text to pass, but to prevent system-level requests (such as COM marshalling) from passing.
  • Can you give an example of what might be best suited to place in the Application_Start and Session_Start subroutines?
    The Application_Start event is guaranteed to occur only once throughout the lifetime of the application. It’s a good place to initialize global variables. For example, you might want to retrieve a list of products from a database table and place the list in application state or the Cache object. SessionStateModule exposes both Session_Start and Session_End events.
  • If I’m developing an application that must accomodate multiple security levels though secure login and my ASP.NET web appplication is spanned across three web-servers (using round-robbin load balancing) what would be the best approach to maintain login-in state for the users?
    No Answer Yet.
  • What are ASP.NET Web Forms? How is this technology different than what is available though ASP?
    Web Forms are the heart and soul of ASP.NET. Web Forms are the User Interface (UI) elements that give your Web applications their look and feel. Web Forms are similar to Windows Forms in that they provide properties, methods, and events for the controls that are placed onto them. However, these UI elements render themselves in the appropriate markup language required by the request, e.g. HTML. If you use Microsoft Visual Studio .NET, you will also get the familiar drag-and-drop interface used to create your UI for your Web application.
  • How does VB.NET/C# achieve polymorphism?
    By using Abstract classes/functions.
  • Can you explain what inheritance is and an example of when you might use it?
    Inheritance is a fundamental feature of an object oriented system and it is simply the ability to inherit data and functionality from a parent object. Rather than developing new objects from scratch, new code can be based on the work of other programmers, adding only new features that are needed.
  • How would you implement inheritance using VB.NET/C#?
    When we set out to implement a class using inheritance, we must first start with an existing class from which we will derive our new subclass. This existing class, or base class, may be part of the .NET system class library framework, it may be part of some other application or .NET assembly, or we may create it as part of our existing application. Once we have a base class, we can then implement one or more subclasses based on that base class. Each of our subclasses will automatically have all of the methods, properties, and events of that base class ? including the implementation behind each method, property, and event. Our subclass can add new methods, properties, and events of its own - extending the original interface with new functionality. Additionally, a subclass can replace the methods and properties of the base class with its own new implementation - effectively overriding the original behavior and replacing it with new behaviors. Essentially inheritance is a way of merging functionality from an existing class into our new subclass. Inheritance also defines rules for how these methods, properties, and events can be merged.
Filed under: .NET, C#, Interviews No Comments
11Nov/100

C# Questions and Answers – 01

  • What’s the advantage of using System.Text.StringBuilder over System.String?
    StringBuilder is more efficient in the cases, where a lot of manipulation is done to the text. Strings are immutable, so each time it’s being operated on, a new instance is created.
  • Can you store multiple data types in System.Array?
    No.
  • What’s the difference between the System.Array.CopyTo() and System.Array.Clone()?
    The first one performs a deep copy of the array, the second one is shallow.
  • How can you sort the elements of the array in descending order?
    By calling Sort() and then Reverse() methods.
  • What’s the .NET datatype that allows the retrieval of data by a unique key?
    HashTable.
  • What’s class SortedList underneath?
    A sorted HashTable.
  • Will finally block get executed if the exception had not occurred?
    Yes.
  • What’s the C# equivalent of C++ catch (…), which was a catch-all statement for any possible exception?
    A catch block that catches the exception of type System.Exception. You can also omit the parameter data type in this case and just write catch {}.
  • Can multiple catch blocks be executed?
    No, once the proper catch code fires off, the control is transferred to the finally block (if there are any), and then whatever follows the finally block.
  • Why is it a bad idea to throw your own exceptions?
    Well, if at that point you know that an error has occurred, then why not write the proper code to handle that error instead of passing a new Exception object to the catch block? Throwing your own exceptions signifies some design flaws in the project.
  • What’s a delegate?
    A delegate object encapsulates a reference to a method. In C++ they were referred to as function pointers.
  • What’s a multicast delegate?
    It’s a delegate that points to and eventually fires off several methods.
  • How’s the DLL Hell problem solved in .NET?
    Assembly versioning allows the application to specify not only the library it needs to run (which was available under Win32), but also the version of the assembly.
  • What are the ways to deploy an assembly?
    An MSI installer, a CAB archive, and XCOPY command.
  • What’s a satellite assembly?
    When you write a multilingual or multi-cultural application in .NET, and want to distribute the core application separately from the localized modules, the localized assemblies that modify the core application are called satellite assemblies.
  • What namespaces are necessary to create a localized application?
    System.Globalization, System.Resources.
  • What’s the difference between // comments, /* */ comments and /// comments?
    Single-line, multi-line and XML documentation comments.
  • How do you generate documentation from the C# file commented properly with a command-line compiler?
    Compile it with a /doc switch.
  • What’s the difference between and XML documentation tag?
    Single line code example and multiple-line code example.
  • Is XML case-sensitive?
    Yes, so and are different elements.
  • What debugging tools come with the .NET SDK?
    CorDBG – command-line debugger, and DbgCLR – graphic debugger. Visual Studio .NET uses the DbgCLR. To use CorDbg, you must compile the original C# file using the /debug switch.
  • What does the This window show in the debugger?
    It points to the object that’s pointed to by this reference. Object’s instance data is shown.
  • What does assert() do?
    In debug compilation, assert takes in a Boolean condition as a parameter, and shows the error dialog if the condition is false. The program proceeds without any interruption if the condition is true.
  • 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.
  • Why are there five tracing levels in System.Diagnostics.TraceSwitcher?
    The tracing dumps can be quite verbose and for some applications that are constantly running you run the risk of overloading the machine and the hard drive there. Five levels range from None to Verbose, allowing to fine-tune the tracing activities.
  • Where is the output of TextWriterTraceListener redirected?
    To the Console or a text file depending on the parameter passed to the constructor.
  • How do you debug an ASP.NET Web application?
    Attach the aspnet_wp.exe process to the DbgClr debugger.
  • What are three test cases you should go through in unit testing?
    Positive test cases (correct data, correct output), negative test cases (broken or missing data, proper handling), exception test cases (exceptions are thrown and caught properly).
  • 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.
  • Explain the three services model (three-tier application).
    Presentation (UI), business (logic and underlying code) and data (from storage or other sources).
  • What are advantages and disadvantages of Microsoft-provided data provider classes in ADO.NET?
    SQLServer.NET data provider is high-speed and robust, but requires SQL Server license purchased from Microsoft. OLE-DB.NET is universal for accessing other sources, like Oracle, DB2, Microsoft Access and Informix, but it’s a .NET layer on top of OLE layer, so not the fastest thing in the world. ODBC.NET is a deprecated layer provided for backward compatibility to ODBC engines.
  • What’s the role of the DataReader class in ADO.NET connections?
    It returns a read-only dataset from the data source when the command is executed.
  • 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%’.
  • Explain ACID rule of thumb for transactions.
    Transaction must be Atomic (it is one unit of work and does not dependent on previous and following transactions), Consistent (data is either committed or roll back, no “in-between” case where something has been updated and something hasn’t), Isolated (no transaction sees the intermediate results of the current transaction), Durable (the values persist if the data had been committed even if the system crashes right after).
  • What connections does Microsoft SQL Server support?
    Windows Authentication (via Active Directory) and SQL Server authentication (via Microsoft SQL Server username and passwords).
  • 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.
  • Why would you use untrusted verificaion?
    Web Services might use it, as well as non-Windows applications.
  • What does the parameter Initial Catalog define inside Connection String?
    The database name to connect to.
  • What’s the data provider name to connect to Access database?
    Microsoft.Access.
  • What does Dispose method do with the connection object?
    Deletes it from the memory.
  • 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.
Filed under: Interviews No Comments
10Nov/100

Stupid Interview Questions

It isn't much fun being a corporate human resources person, but the job offers one treat: You get to dream up outlandish interview questions to throw at job candidates, then watch them squirm. Some of these goofy questions are time-honored -- they may not be useful, but they've become an HR tradition. Others are hot off the press. Here's a tour through the world of wacky queries -- so you'll be prepared the next time you're hit with one in an interview:

Where do you see yourself in five years?
This is the great-granddaddy of goofy questions, and I give you permission, if you have any misgivings about a job opportunity, to walk out the door when you hear it. It's such a time-waster that only the most hidebound interviewers will utter it, but it lives on.

Here's why it's dumb. No company will guarantee you a job for five years, much less a career path. To construct such a plan for yourself, you'd have to make predictions about industries, companies, and your likes and dislikes that could only serve to constrain your choices. And in any case, why is it so all-fired important to have a dang career plan in mind? Every successful entrepreneur and many top corporate people will tell you their key to success: I did what I felt driven to do at the moment.

So when you get asked this question, you can say: "I intend to be happy and productive five years from now, working at a job I love in a company that values my talents" and leave it at that. Or you can give the expected answer and say: "I hope to be three levels up the ladder, here at Happy Corp." Or you can say: "I hope to own this company," just to shake things up.

But for an interviewer to ask the question at all is a bad sign. Come on, people! There are millions of thoughts in the human brain. Can we change the ones we use in job interviews every decade or so?

If you were an animal/a can of soup/some other random object, which one would you be?
This is a question typically asked of new grads, because it's considered cute. It's supposed to test how people think. But it's asinine. You can pretend to think about your answer for a moment (eyes to the ceiling, chin resting on hand) and then come up with something. Or stare blankly at the interviewer and say, deadpan: "Are you serious?" Or try one of these answers:

(Animal) "Oh, any crepuscular animal would do well for me -- a rabbit or a bat, perhaps." (Crepuscular means most active during dawn and dusk, so you'll get to show off your extensive vocab.)

(Soup) "Probably the low-sodium chicken broth." Fix the interviewer with a penetrating gaze -- she won't know whether you're mocking her imbecilic question or are deadly serious.

What are your weaknesses?
By now, such a large percentage of the job-seeking public has gotten clued in on the politically correct answer to this one -- which is, "I'm a hopeless workaholic" -- that the question's utility is limited. But it's also offensive.

This is a job interview, not a psychological exam. It's one thing for an interviewer to ask you what you do particularly well. It's another thing to ask what you don't do well and expect to get a forthright answer -- in a context where it's clear to both parties that you're being weeded in or out. The most honest answer might be this: "That's for me to know and you to find out." But that won't help your chances.

So if you can't bear to repeat the "workaholic" line, I'd say something that is true of yourself but also terribly common -- like the fact that you get bored easily, or prefer numbers to people or vice versa. None of these is actually a weakness, but that's O.K.

What in particular interested you about our company?
Now, on one level this is a reasonable question. If you say: "I'm interested in this job because it's three blocks from my apartment," you might not be the world's best candidate. But the disingenuous, and therefore offensive, aspect of this question is that it assumes that you have unlimited job opportunities and have pinpointed this one because of some dazzling aspect of the role or the company.

I mean, please. Most of the job-seeking population is living on the lower two-thirds of Maslow's pyramid, where the most appealing thing about any job is that you got the darned interview. Why am I interested? Because you guys called me back. But you can't say that, so you have to rhapsodize about the company's wonderful products and services and the world-class management team and so on.

Now, it's important to show that you know a lot about the company. But you have lots of ways to demonstrate that in an interview (and lots of ways for the interviewer to ask you to do so) without pretending that the company had to fight every employer in town to get an audience with you. Everybody involved knows the company is shredding 10 times the number of résumés it's reading, so let's not pretend it was your breathtaking credentials that got you the interview. It was the fact that the company responded to your overture, unlike 90% of the employers you contacted.

Below the director level or so, where it might be reasonable to assume you sought out the company for particular job-hunting attention, it's not necessary to pretend that you carefully chose it from a raft of others pursuing you. So unless you approached the outfit in the absence of a posted job opportunity, it's just silly to ask: "Why us?"

Rather, the interviewer can say: "When you saw our ad on Monster.com, what made you respond?" And, of course, the logical answer is: "Because I know I can do the job that was posted." Duh. No one said job-hunting was easy.

What would your past managers say about you?
This is a fine question, but it's not a true interview question. It's an intelligence question. It's like the question on one of those "honesty" tests that are becoming more and more popular in the hiring process (to add insult to injury, they're often called Personality Profiles): "Do you think it's O.K. to steal from your employer?"

These are intelligence questions because you have to have the intelligence to know the answer in order to be smart enough to go and get a job.

The trick here is to say something sufficiently witty or pithy to make you stand out from the crowd, because the standard answers are so tired: My managers would say that I'm hard-working, loyal, reliable, and a great team player. Snoozeville.

Why not try: My past managers would say that I was an outstanding individual contributor who also supported the team 100%. Or: My managers would say that I came up with breakthrough solutions while never losing track of the bottom line. You can probably dream up something better.

The point is, this is a softball: Don't think too much about it. It says more about the interviewer (who lacks the moxie to think up unique or penetrating questions) than it ever will about you.

The secret of good job interviewers is that they never ask traditional, dorky interview questions. They don't need to. They jump into a business conversation that does three powerful things in a one-hour chat:

a) Gets you excited about this opportunity (or, as valuably, makes it clear that you and this job are not a good fit)
b) Reveals to the interviewer how you'll fit into the role and the company, based on your background, perspective, temperament, and ideas
c) Gives you a ton of new information about the job, the management, the goals, the culture, and what life at this joint would be like.

If any of this doesn't happen, it's a problem. If you're lukewarm on the job when you leave the interview, or if you don't feel you've had a chance to show what you know and how you think, or -- worst of all -- if the interviewer used your time together to satisfy his need for more information about you while sharing almost nothing about the job, that's an enormous red flag.

And if you get called back for a second interview while you're still information-deprived, say so. "I'm interested in learning more about the opportunity before a second interview," you can say. "Would a phone call with the hiring manager be an effective way to help me get up to speed?" That kind of suggestion respects the hiring manager's time and won't waste yours on a second, no-new-data interview.

Try it. You might save yourself some aggravation -- along with some extra time you can use to work on your five-year career plan and on tackling those pesky weaknesses of yours before the next interview.

Filed under: Interviews No Comments