Automatically adding namespace

Scenario: Consider that u want to use a class but u don't know under which namespace the class belong.
Here the solution: keep the cursor on the class that u r using and press 'Alt+Shift+F10' a new popup menu will occur which will show the namespace just click on the popup menu the name space will automatically added in the starting of ur code.

Example:
using System;
Regex clsReg = new Regex(); here Regex is a class which comes under System.Text.RegularExpressions namespace but u didnt include it in ur code

now keep the cursor on Regex and press alt+shit+F10 a popup menu will occur like the below image.









then click the using System.Text.RegularExpressions;
now u go and see the starting page of ur code.


Note: This technique will workout for all the built in classes also for the classes which are added in the reference.

IS IT POSSIBLE TO USE INNER JOIN QUERY IN A DATASET

Scenario: U have 2 tables in ur dataset with both the table contains a column name 'Samecolumn'
Table1: Samecolumn has the following 3 value
col1
col2
col3
Table2: Samecolumn has the following 2 value
col2
col3
Is it possible to query in the dataset to get the ouput of 2 rows i.e) col2, col3

Solution: No, There is no direct way to get the child rows
DataRelation and get joined rows, you will need to use the GetChildRows method of DataRow and pass the DataRelation object.
The following code example creates a DataRelation between the Customers
table and the Orders table of a DataSet and returns all the orders for each
customer.

Dim custOrderRel As DataRelation = custDataset.Relations.Add("CustOrders", _
custDS.Tables("Table1").Columns("Samecolumn"), _
custDS.Tables("Table2").Columns("Samecolumn"))

Dim custRow As DataRow
Dim orderRow As DataRow

For Each custRow in custDataset.Tables("Table1").Rows
Console.WriteLine(custRow("Samecolumn"))
For Each orderRow in custRow.GetChildRows(custOrderRel)
Console.WriteLine(orderRow("Samecolumn"))
Next
Next

Rare images

Find rowindex in dataset based on datarow, Set primary key to dataset

//To SETS THE DATASET PRIMARY KEY
DataCoulumn[] keys = new DataColumn[1];
keys[0] = DataSet.Tables["mytable"].Column["i_ID"];
DataSet.Tables["mytable"].PrimaryKey = keys;

// To Bind in THE DATAGRID VIEW
BindingManagerBase bm;
DataGridView1.DataSource = DataSet.Tables["mytable"].DefaultView;
bm = this.DataGridView1.BindingContext[this.DataGridView1.DataSource, this. DataGridView1.DataMember];

//You have a datarow and u need to find the rowindex of the row in dataset
DataRow findRow = DataSet.Tables["mytable"].Rows.Find(((DataRowView)bm.Current).Row[0]); // Row[0] is the collumn to seach in in this case ID column
int indexNumber = DataSet.Tables["mytable"].Rows.IndexOF(findRow);

 

Ping a machine using c#.net

Name space: using System.Net.NetworkInformation;
try
{
Ping oping = new Ping();
PingReply oReply = oping.Send(machineipaddress);
if (oReply.Status.ToString().ToLower() != "success")
{
MessageBox.Show("Unable to ping the machine " + machineipaddress + "\n\n\t" + oReply.Status);
Environment.Exit(0);
}
}
catch (PingException ex)
{
MessageBox.Show("Error while pinging the machine " + machineipaddress + "\n\n" + ex.Message);
Environment.Exit(0);
}

.net windows forms interview question

  1. Can you write a class without specifying namespace? Which namespace does it belong to by default??
    Yes, you can, then the class belongs to global namespace which has no name. For commercial products, naturally, you wouldn't want global namespace.
  2. You are designing a GUI application with a window and several widgets on it. The user then resizes the app window and sees a lot of grey space, while the widgets stay in place. What's the problem? One should use anchoring for correct resizing. Otherwise the default property of a widget on a form is top-left, so it stays at the same location when resized.
  3. How can you save the desired properties of Windows Forms application? .config files in .NET are supported through the API to allow storing and retrieving information. They are nothing more than simple XML files, sort of like what .ini files were before for Win32 apps.
  4. So how do you retrieve the customized properties of a .NET application from XML .config file? Initialize an instance of AppSettingsReader class. Call the GetValue method of AppSettingsReader class, passing in the name of the property and the type expected. Assign the result to the appropriate variable.
  5. Can you automate this process? In Visual Studio yes, use Dynamic Properties for automatic .config creation, storage and retrieval.
  6. My progress bar freezes up and dialog window shows blank, when an intensive background process takes over. Yes, you should've multi-threaded your GUI, with taskbar and main form being one thread, and the background process being the other.
  7. What's the safest way to deploy a Windows Forms app? Web deployment: the user always downloads the latest version of the code; the program runs within security sandbox, properly written app will not require additional security privileges.
  8. Why is it not a good idea to insert code into InitializeComponent method when working with Visual Studio? The designer will likely throw it away; most of the code inside InitializeComponent is auto-generated.
  9. What's the difference between WindowsDefaultLocation and WindowsDefaultBounds? WindowsDefaultLocation tells the form to start up at a location selected by OS, but with internally specified size. WindowsDefaultBounds delegates both size and starting position choices to the OS.
  10. What's the difference between Move and LocationChanged? Resize and SizeChanged? Both methods do the same, Move and Resize are the names adopted from VB to ease migration to C#.
  11. How would you create a non-rectangular window, let's say an ellipse? Create a rectangular form, set the TransparencyKey property to the same value as BackColor, which will effectively make the background of the form transparent. Then set the FormBorderStyle to FormBorderStyle.None, which will remove the contour and contents of the form.
  12. How do you create a separator in the Menu Designer? A hyphen '-' would do it. Also, an ampersand '&\' would underline the next letter.
  13. How's anchoring different from docking? Anchoring treats the component as having the absolute size and adjusts its location relative to the parent form. Docking treats the component location as absolute and disregards the component size. So if a status bar must always be at the bottom no matter what, use docking. If a button should be on the top right, but change its position with the form being resized, use anchoring.

 

Asp.net interview Questions

1.      Describe the role of inetinfo.exe, aspnet_isapi.dll andaspnet_wp.exe in the page loading process. inetinfo.exe is theMicrosoft IIS server running, handling ASP.NET requests among other things.When an ASP.NET request is received (usually a file with .aspx extension),the ISAPI filter aspnet_isapi.dll takes care of it by passing the request tothe actual worker process aspnet_wp.exe.

2.      What's the difference between Response.Write() andResponse.Output.Write()? The latter one allows you to write formattedoutput.

3.      What methods are fired during the page load? Init() - when the pageis instantiated, Load() - when the page is loaded into server memory,PreRender() - the brief moment before the page is displayed to the user asHTML, Unload() - when page finishes loading.

4.      Where does the Web page belong in the .NET Framework class hierarchy?System.Web.UI.Page

5.      Where do you store the information about the user's locale? System.Web.UI.Page.Culture

6.      What's the difference between Codebehind="MyCode.aspx.cs" andSrc="MyCode.aspx.cs"? CodeBehind is relevant to Visual Studio.NET only.

7.      What's a bubbled event? When you have a complex control, like DataGrid, writing an event processing routine for each object (cell, button, row, etc.) is quite tedious. The controls can bubble up their eventhandlers, allowing the main DataGrid event handler to take care of its constituents.

8.      Suppose you want a certain ASP.NET function executed on MouseOver overa certain button. Where do you add an event handler? It's the Attributesproperty, the Add function inside that property. So btnSubmit.Attributes.Add("onMouseOver","someClientCode();")

9.      What data type does the RangeValidator control support? Integer,String and Date.

10.  Explain the differences between Server-side and Client-side code?  Server-side code runs on the server. Client-side code runs in the clients' browser.

11.  What type of code (server or client) is found in a Code-Behind class? Server-side code.

12.  Should validation (did the user enter a real date) occur server-side or client-side? Why? Client-side. This reduces an additional request to the server to validate the users input.

13.  What does the "EnableViewState" property do? Why would I want it on or off?  It enables the viewstate on the page. It allows the page to save the users input on a form.

14.  What is the difference between Server.Transfer and Response.Redirect? Why would I choose one over the other? Server.Transfer is used to post a form to another page. Response.Redirect is used to redirect the user to another page or site.

15.  Can you explain the difference between an ADO.NET Dataset and an ADO Recordset?

·         A DataSet can represent an entire relational database in memory, complete with tables, relations, and views.

·         A DataSet is designed to work without any continuing connection to the original data source.

·         Data in a DataSet is bulk-loaded, rather than being loaded on demand.

·         There's no concept of cursor types in a DataSet.

·         DataSets have no current record pointer You can use For Each loops to move through the data.

·         You can store many edits in a DataSet, and write them to the original data source in a single operation.

·         Though the DataSet is universal, other objects in ADO.NET come in different versions for different data sources.

16.  Can you give an example of what might be best suited to place in the Application_Start and Session_Start subroutines?  This is where you can set the specific variables for the Application and Session objects.

17.  If I'm developing an application that must accommodate multiple security levels though secure login and my ASP.NET web application is spanned across three web-servers (using round-robin load balancing) what would be the best approach to maintain login-in state for the users? Maintain the login state security through a database.

18.  Can you explain what inheritance is and an example of when you might use it? When you want to inherit (use the functionality of) another class. Base Class Employee. A Manager class could be derived from the Employee base class.

19.  Whats an assembly?  Assemblies are the building blocks of the .NET framework. Overview of assemblies from MSDN

20.  Describe the difference between inline and code behind. Inline code written along side the html in a page. Code-behind is code written in a separate file and referenced by the .aspx page.

21.  Explain what a diffgram is, and a good use for one? The DiffGram is one of the two XML formats that you can use to render DataSet object contents to XML. For reading database data to an XML file to be sent to a Web Service.

22.  Whats MSIL, and why should my developers need an appreciation of it if at all? MSIL is the Microsoft Intermediate Language. All .NET compatible languages will get converted to MSIL.

23.  Which method do you invoke on the DataAdapter control to load your generated dataset with data? The .Fill() method

24.  Can you edit data in the Repeater control?  No, it just reads the information from its data source

25.  Which template must you provide, in order to display data in a Repeater control? ItemTemplate

26.  How can you provide an alternating color scheme in a Repeater control? Use the AlternatingItemTemplate

27.  What property must you set, and what method must you call in your code, in order to bind the data from some data source to the Repeater control? You must set the DataSource property and call the DataBind method.

28.  What base class do all Web Forms inherit from?  The Page class.

29.  Name two properties common in every validation control? ControlToValidate property and Text property.

30.  What tags do you need to add within the asp:datagrid tags to bind columns manually? Set AutoGenerateColumns Property to false on the datagrid tag

31.  What tag do you use to add a hyperlink column to the DataGrid? <asp:HyperLinkColumn>

32.  What is the transport protocol you use to call a Web service? SOAP is the preferred protocol.

33.  True or False: A Web service can only be written in .NET? False

34.  What does WSDL stand for? (Web Services Description Language)

35.  Where on the Internet would you look for Web services? (http://www.uddi.org)

36.  Which property on a Combo Box do you set with a column name, prior to setting the DataSource, to display data in the combo box? DataTextField property

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

38.  True or False: To test a Web service you must create a windows application or Web application to consume this service? False, the webservice comes with a test page and it provides HTTP-GET method to test.

39.  How many classes can a single .NET DLL contain?  It can contain many classes.

C# interview Questions

  1. What's the implicit name of the parameter that gets passed into the class' set method? Value, and its datatype depends on whatever variable we're changing.
  2. How do you inherit from a class in C#? Place a colon and then the name of the base class. Notice that it's double colon in C++.
  3. Does C# support multiple inheritance? No, use interfaces instead.
  4. When you inherit a protected class-level variable, who is it available to? Classes in the same namespace.
  5. Are private class-level variables inherited? Yes, but they are not accessible, so looking at it you can honestly say that they are not inherited. But they are.
  6. Describe the accessibility modifier protected internal. It's available to derived classes and classes within the same Assembly (and naturally from the base class it's declared in).
  7. C# provides a default constructor for me. I write a constructor that takes a string as a parameter, but want to keep the no parameter one. How many constructors should I write? Two. Once you write at least one constructor, C# cancels the freebie constructor, and now you have to write one yourself, even if there's no implementation in it.
  8. What's the top .NET class that everything is derived from? System.Object.
  9. How's method overriding different from overloading? When overriding, you change the method behavior for a derived class. Overloading simply involves having a method with the same name within the class.
  10. What does the keyword virtual mean in the method definition? The method can be over-ridden.
  11. Can you declare the override method static while the original method is non-static? No, you can't, the signature of the virtual method must remain the same, only the keyword virtual is changed to keyword override.
  12. Can you override private virtual methods? No, moreover, you cannot access private methods in inherited classes, have to be protected in the base class to allow any sort of access.
  13. Can you prevent your class from being inherited and becoming a base class for some other classes? Yes, that's what keyword sealed in the class definition is for. The developer trying to derive from your class will get a message: cannot inherit from Sealed class WhateverBaseClassName. It's the same concept as final class in Java.
  14. Can you allow class to be inherited, but prevent the method from being over-ridden? Yes, just leave the class public and make the method sealed.
  15. What's an abstract class? A class that cannot be instantiated. A concept in C++ known as pure virtual method. A class that must be inherited and have the methods over-ridden. Essentially, it's a blueprint for a class without any implementation.
  16. When do you absolutely have to declare a class as abstract (as opposed to free-willed educated choice or decision based on UML diagram)? When at least one of the methods in the class is abstract. When the class itself is inherited from an abstract class, but not all base abstract methods have been over-ridden.
  17. What's an interface class? It's an abstract class with public abstract methods all of which must be implemented in the inherited classes.
  18. Why can't you specify the accessibility modifier for methods inside the interface? They all must be public. Therefore, to prevent you from getting the false impression that you have any freedom of choice, you are not allowed to specify any accessibility, it's public by default.
  19. Can you inherit multiple interfaces? Yes, why not.
  20. And if they have conflicting method names? It's up to you to implement the method inside your own class, so implementation is left entirely up to you. This might cause a problem on a higher-level scale if similarly named methods from different interfaces expect different data, but as far as compiler cares you're okay.
  21. What's the difference between an interface and abstract class? In the interface all methods must be abstract; in the abstract class some methods can be concrete. In the interface no accessibility modifiers are allowed, which is ok in abstract classes.
  22. How can you overload a method? Different parameter data types, different number of parameters, different order of parameters.
  23. If a base class has a bunch of overloaded constructors, and an inherited class has another bunch of overloaded constructors, can you enforce a call from an inherited constructor to an arbitrary base constructor? Yes, just place a colon, and then keyword base (parameter list to invoke the appropriate constructor) in the overloaded constructor definition inside the inherited class.
  24. What's the difference between System.String and System.StringBuilder classes? System.String is immutable; System.StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed.
  25. What's the advantage of using System.Text.StringBuilder over System.String? StringBuilder is more efficient in the cases, where a lot of manipulation is done to the text. Strings are immutable, so each time it's being operated on, a new instance is created.
  26. Can you store multiple data types in System.Array? No.
  27. What's the difference between the System.Array.CopyTo() and System.Array.Clone()? The first one performs a deep copy of the array, the second one is shallow.
  28. How can you sort the elements of the array in descending order? By calling Sort() and then Reverse() methods.
  29. What's the .NET datatype that allows the retrieval of data by a unique key? HashTable.
  30. What's class SortedList underneath? A sorted HashTable.
  31. Will finally block get executed if the exception had not occurred? Yes.
  32. What's the C# equivalent of C++ catch (…), which was a catch-all statement for any possible exception? A catch block that catches the exception of type System.Exception. You can also omit the parameter data type in this case and just write catch {}.
  33. Can multiple catch blocks be executed? No, once the proper catch code fires off, the control is transferred to the finally block (if there are any), and then whatever follows the finally block.
  34. Why is it a bad idea to throw your own exceptions? Well, if at that point you know that an error has occurred, then why not write the proper code to handle that error instead of passing a new Exception object to the catch block? Throwing your own exceptions signifies some design flaws in the project.
  35. What's a delegate? A delegate object encapsulates a reference to a method. In C++ they were referred to as function pointers.
  36. What's a multicast delegate? It's a delegate that points to and eventually fires off several methods.
  37. How's the DLL Hell problem solved in .NET? Assembly versioning allows the application to specify not only the library it needs to run (which was available under Win32), but also the version of the assembly.
  38. What are the ways to deploy an assembly? An MSI installer, a CAB archive, and XCOPY command.
  39. What's a satellite assembly? When you write a multilingual or multi-cultural application in .NET, and want to distribute the core application separately from the localized modules, the localized assemblies that modify the core application are called satellite assemblies.
  40. What namespaces are necessary to create a localized application? System.Globalization, System.Resources.
  41. What's the difference between // comments, /* */ comments and /// comments? Single-line, multi-line and XML documentation comments.
  42. How do you generate documentation from the C# file commented properly with a command-line compiler? Compile it with a /doc switch.
  43. What's the difference between <c> and <code> XML documentation tag? Single line code example and multiple-line code example.
  44. Is XML case-sensitive? Yes, so <Student> and <student> are different elements.
  45. What debugging tools come with the .NET SDK? CorDBG – command-line debugger, and DbgCLR – graphic debugger. Visual Studio .NET uses the DbgCLR. To use CorDbg, you must compile the original C# file using the /debug switch.
  46. What does the This window show in the debugger? It points to the object that's pointed to by this reference. Object's instance data is shown.
  47. What does assert() do? In debug compilation, assert takes in a Boolean condition as a parameter, and shows the error dialog if the condition is false. The program proceeds without any interruption if the condition is true.
  48. What's the difference between the Debug class and Trace class? Documentation looks the same. Use Debug class for debug builds, use Trace class for both debug and release builds.
  49. Why are there five tracing levels in System.Diagnostics.TraceSwitcher? The tracing dumps can be quite verbose and for some applications that are constantly running you run the risk of overloading the machine and the hard drive there. Five levels range from None to Verbose, allowing to fine-tune the tracing activities.
  50. Where is the output of TextWriterTraceListener redirected? To the Console or a text file depending on the parameter passed to the constructor.
  51. How do you debug an ASP.NET Web application? Attach the aspnet_wp.exe process to the DbgClr debugger.
  52. What are three test cases you should go through in unit testing? Positive test cases (correct data, correct output), negative test cases (broken or missing data, proper handling), exception test cases (exceptions are thrown and caught properly).
  53. Can you change the value of a variable while debugging a C# application? Yes, if you are debugging via Visual Studio.NET, just go to Immediate window.
  54. Explain the three services model (three-tier application). Presentation (UI), business (logic and underlying code) and data (from storage or other sources).
  55. What are advantages and disadvantages of Microsoft-provided data provider classes in ADO.NET? SQLServer.NET data provider is high-speed and robust, but requires SQL Server license purchased from Microsoft. OLE-DB.NET is universal for accessing other sources, like Oracle, DB2, Microsoft Access and Informix, but it's a .NET layer on top of OLE layer, so not the fastest thing in the world. ODBC.NET is a deprecated layer provided for backward compatibility to ODBC engines.
  56. What's the role of the DataReader class in ADO.NET connections? It returns a read-only dataset from the data source when the command is executed.
  57. What is the wildcard character in SQL? Let's say you want to query database with LIKE for all employees whose name starts with La. The wildcard character is %, the proper query with LIKE would involve 'La%'.
  58. Explain ACID rule of thumb for transactions. Transaction must be Atomic (it is one unit of work and does not dependent on previous and following transactions), Consistent (data is either committed or roll back, no "in-between" case where something has been updated and something hasn't), Isolated (no transaction sees the intermediate results of the current transaction), Durable (the values persist if the data had been committed even if the system crashes right after).
  59. What connections does Microsoft SQL Server support? Windows Authentication (via Active Directory) and SQL Server authentication (via Microsoft SQL Server username and passwords).
  60. Which one is trusted and which one is untrusted? Windows Authentication is trusted because the username and password are checked with the Active Directory, the SQL Server authentication is untrusted, since SQL Server is the only verifier participating in the transaction.
  61. Why would you use untrusted verificaion? Web Services might use it, as well as non-Windows applications.
  62. What does the parameter Initial Catalog define inside Connection String? The database name to connect to.
  63. What's the data provider name to connect to Access database? Microsoft.Access.
  64. What does Dispose method do with the connection object? Deletes it from the memory.
  65. What is a pre-requisite for connection pooling? Multiple processes must agree that they will share the same connection, where every parameter is the same, including the security settings.

 

Useful C# for interview point II

within a class:
main must be a static method
In a static class we cant able to declare non static methods
In a non static class we can able to declare static methods
From a static method we cant able to call non static method. if need use an object for that class
From a non static method we can able to call static method
Two Non static classes:
From a non static method we cant call a non static method. need to create object for the class
From a non static method we cant call a static method. only able by using class name and dot(.)
From a static method we cant call a static method. only able by using class name and dot(.)
From a static method we cant call a non static method. need to create object for the class
Two static classes:
Cant able to create object for classs
From a static method we can call a static method. only able by using class name and dot(.)

Cant able to override non virtual or static methods
Cant able to create instance for interface or abstact class
you can use a cast to create an instance for an interface in C#
Cant able to inherit abstract method but able abstract class
Cant able to derive a sealed class
interface has only method declaration bcoz all method in interface are public and abstaract, Abstract method does not have any body
Abstract class have both abstract and nonabstract methodes.so those abstract methods only have declaration and non ablstract method have body also.
All abstract methods must implemented while using the abstract class or interface
Non abstract class doesnot contain abstract method
Boxing:
Value type to object type-implicit-compiler will do
unboxing
object type to value type-explicit-using type cast
We can override the base class method from deri class, only if the the base class method is virtual or abstract

Unlike base classes, interfaces don't implement any of their members by providing the actual code for properties, methods, and so on. Interfaces are just specifications for those members, and if your class implements an interface, it must provide code for all the members of that interface.
Delegates let you pass methods as parameters. They provide you with another form of polymorphism, because you can assign methods to delegates at runtime, leaving the rest of your code unchanged but calling the methods you specify at runtime.
No special impact for the delegate on static methods
BufferedStream object, which will use its own internal buffer to maximize performance

we've simply read data from a file and waited for the read operation to finish before doing anything. As we start working with network I/O, where things can be a lot slower, it won't be as easy to wait for reading and writing operations to complete. For that reason, the .NET Framework supports asynchronous I/O through the BeginRead and BeginWrite methods of the Stream class. You can call BeginRead to read a bufferfull of data, or BeginWrite to write a bufferfull of data, and then go on to do other work

C# enables you to save an entire object, including all its data (called an object-graph) through a process called serialization. Serialization lets you write entire objects out to disk and read them back in later. Objects that pass between assembly boundaries (through a process called marshalling) are also serialized.

The common language runtime does not support static variables in methods.

You don't have to serialize all the members of an object; for example, if you have a huge array filled with sequential numbers that's easy to re-create, there's no benefit to taking up a great deal of disk space by storing that array to memory. To mark members that you don't want serialized, you use the [NonSerialized] attribute.
if you didn't want to serialize the data array in ch05_13.cs, you could mark it with [NonSerialized]; note that when you use this attribute, you should implement the IDeserializationCallback interface,

Isolated storage saves data for your application that you might have stored in the Registry before.To store data in isolated storage, you use the IsolatedStorageFileStream class;(used to store configuration data)

You can also create arrays of arrays, called jagged arrays because they need not be rectangular.Here's the syntax you use to create an array of arrays.

Answer: Web services are programmable business logic components that provide access to functionality through the Internet. Standard protocols like HTTP can be used to access them. Web services are based on the Simple Object Access Protocol (SOAP), which is an application of XML. Web services are given the .asmx extension..

out and ref are reference type diff is ref must initialize.but out does not must be initialized

Eval is used for unidirectional (readonly) data binding, while Bind is for bi-directional (editable) databinding.

The Eval method is a static (read-only) method that takes the value of a data field and returns it as a string. The Bind method supports read/write functionality with the ability to retrieve the values of data-bound controls and submit any changes made back to the database.

DataSet is just a collection of DataTable objects

DataSet is an in-memory representation of data, containing one or more DataTables. A DataTable is an in-memory representation of data, typically retrieved from a database or XML source.
A DataView is a view onto an in-memory representation of data held in a DataTable.

Useful C# for interview point

Note that because static methods are not part of an object, you cannot use the this keyword
in such methods. It's important to know that static methods cannot directly access non-static
members (which means, for example, that you cannot call a non-static method from a static
method). Instead, they must instantiate an object and use the members of that object to
access non-static members .

Static constructors are called before any objects(constructor) are created from your class

what's the difference between new and override? You use new when you're replacing a
base class method with the same signature, and you use override when you're customizing it
in the current class.

Power of the DataView

The Power of the DataView


Introduction

Its hard to imagine what the creators of ADO.NET were thinking as they were designing it. It has been challenge enough just understanding and mastering all of the many objects and their capabilities. Just think, to physically access a column of data you have to now maneuver through at least five objects instead of two in ADO.

As part of my effort to learn ADO.NET, I decided to first determine how to reproduce the basic functionality that I had in ADO, especially with the Recordset. That is where I discovered the new and many uses of the DataView class (although I prefer the term object to class).

Think about the following code snippet:

objRS.Sort = "CompanyName"
objRS.Filter = "Country = " & strCountry
If Not objRS.EOF Then
Do Until objRS.EOF
...
ObjRS.MoveNext
Loop
End If
objRS.Filter = 0
objRS.Sort = ""

If the Recordset was the order detail for a customer, the sort order was specified on OrderNumber followed by ProductName. Then we used the marvelous Filter method of the Recordset to create a view of only those records we wished to work with. After we were through, we removed both the sort and the filter to perform any other tasks that were necessary.

When I first started working with ADO.NET, I just couldnt seem to figure out how to easily reproduce this functionality. Sure, you can bind a DataSet to a grid with just two lines of code. But where were examples of how to perform tasks where I needed more than just databinding to a DataTable? Thats when I stumbled across the DataView class.

I like to use the following analogy. DataSets are very much like simple, stand-alone databases. They contain tables called DataTables with rows and columns. These tables can have relationships. They also contain views called DataViews. The DataView class is very similar to a database view that you would create in Oracle or SQL Server. You can use a DataView just about anywhere you can use a DataTable. Yet they contain some additional properties and methods that a DataTable does not.

Sorting, Finding and Filtering

Three of the most useful things that you can do with a DataView are sorting, finding specific rows and filtering unwanted records. If I could do these things with a view, then I could reproduce the code snippet above using ADO.NET:

Dim dv As DataView
dv = New DataView(DataSet1.Tables("Customers"))
dv.Sort = "CompanyName"
dv.RowFilter = "Country = " & strCountry

At this point you can either Bind the view to one of the ASP.NET server side controls or you can process each row individually:

Dim i As Integer
For i = 0 To dv.count - 1
' perform your logic here
Next

In ADO.NET, there is no MoveFirst, MoveNext, MovePrior or MoveLast. Nor is there EOF or BOF. The data is all referenced as an array. To see if data is present, just check the Count property of the DataView (no more EOF runtime errors!). Remember that arrays begin at 0 and not 1.

If you want to filter rows with null values, you must first convert the null values to something such as a string:

dv.RowFilter = "Isnull(Col1,'Null') = 'Null'"

Only the Tip of the Iceberg

DataViews are also useful for other things than just the functions that we just discussed. Think about this: Every table has at least one DataView, which is a view of itself. This is called the DefaultView. That means that if you reference a table by its DefaultView, it can do anything a DataView can do as well:

DataSet1.Tables(0).DefaultView.Sort = "CompanyName"
DataSet1.Tables(0).DefaultView.RowFilter = "Country = " & strCountry
MyDataGrid.DataSource = DataSet1.Tables(0).DefaultView
MyDataGrid.DataBind()

Another great feature of DataViews is that you can create them with the RowFilter and Sort already specified:

Dim dv As New DataView(ds.Tables("Country"), _
"Country = 'UK'", _
"CompanyName", _
DataRowViewState.CurrentRows)

DataView Differences

Of course, the DataView is not a DataTable. The most obvious difference is that DataViews are comprised of DataRowViews where as a table contains DataRows. DataRowViews do not contain a Columns collection, but an Item property to reference the underlying column. And editing data in a DataRowView is also different. But there is one trick that you can play on the DataRowView. Just like every table has a DefaultDataView property, the DataRowView has a Row property that is an actual reference to the underlying DataRow:

Dim drv As DataRowView
For Each drv In dv
Response.Write(drv.Rows("CompanyName") & "<br>")
Next drv

Conclusion

As you can see, this is just one of the many areas where ADO.NET differs dramatically from ADO. Now that Ive discovered the DataView, Ive been able to reproduce the functionality that was in my old ASP application in my new ASP.NET applications. And with a little more practice, I hope to even overcome obstacles that were present with the Recordset.

Generics

What Are Generics?

Generics allow you to realize type safety at compile time. They allow you to create a data structure without committing to a specific data type. When the data structure is used, however, the compiler makes sure that the types used with it are consistent for type safety. Generics provide type safety, but without any loss of performance or code bloat. While they are similar to templates in C++ in this regard, they are very different in their implementation.

Using Generics Collections

The System.Collections.Generics namespace contains the generics collections

Y Generics

ex:

List<int> aList = new List<int>();
aList.Add(3);
aList.Add(4);
aList.Add(5.0);
int total = 0;
foreach(int val in aList)
{
total = total + val;
}
This will cause an compiler error bcoz not able to cast the double5.0 to integer
But the same was handled as error at runtime while using arraylist.

CLR Support for Generics



Generics is not a mere language-level feature. The .NET CLR recognizes generics. In
that regard, the use of generics is a first-class feature in .NET. For each type of parameter used for
a generic, a class is not rolled out in the Microsoft Intermediate Language (MSIL). In
other words, your assembly contains only one definition of your parameterized data
structure or class, irrespective of how many different types are used for that parameterized
type. For instance, if you define a generic type MyList, only one definition of that
type is present in MSIL. When the program executes, different classes are dynamically created,
one for each type for the parameterized type. If you use MyList and
MyList, then two classes are created on the fly when your program executes.



Writing a generic class




//MyList.cs
#region Using directives

using System;
using System.Collections.Generic;
using System.Text;

#endregion

namespace CLRSupportExample
{
public class MyList
{
private static int objCount = 0;

public MyList()
{
objCount++;
}

public int Count
{
get
{
return objCount;
}
}
}
}

//Program.cs
#region Using directives

using System;
using System.Collections.Generic;
using System.Text;

#endregion

namespace CLRSupportExample
{
class SampleClass {}

class Program
{
static void Main(string[] args)
{
MyList myIntList = new MyList();
MyList myIntList2 = new MyList();

MyList myDoubleList
= new MyList();

MyList mySampleList
= new MyList();

Console.WriteLine(myIntList.Count);
Console.WriteLine(myIntList2.Count);
Console.WriteLine(myDoubleList.Count);
Console.WriteLine(mySampleList.Count);
Console.WriteLine(
new MyList().Count);

Console.ReadLine();
}
}
}


I have created a generic class named MyList. To parameterize it, I simply inserted an angle
bracket. The T within <> represents the actual type that will be specified when the
class is used. Within the MyList class, I have a static field, objCount. I am incrementing this
within the constructor so I can find out how many objects of that type are created by the
user of my class. The Count property returns the number of instances of the same type as
the instance on which it is called.



In the Main() method, I am creating two instances of MyList, one instance of
MyList, and two instances of MyList, where
SampleClass is a
class I have defined. The question is: what will be the value of Count? That is, what is the
output from the above program? Go ahead and think on this and try to answer this
question before you read further.



Have you worked the above question? Did you get the following answer?




2
2
1
1
2

Generics Methods



In addition to having generic classes, you may also have generic methods. Generic methods
may be part of any class. Let's look at Example 4:



Example 4. A generic method




public class Program
{
public static void Copy(List source, List destination)
{
foreach (T obj in source)
{
destination.Add(obj);
}
}

static void Main(string[] args)
{
List lst1 = new List();
lst1.Add(2);
lst1.Add(4);

List lst2 = new List();
Copy(lst1, lst2);
Console.WriteLine(lst2.Count);
}
}


The Copy() method is a generic method that works with the parameterized type T.
When Copy() is invoked in Main(), the compiler figures out the specific
type to use, based on the arguments presented to the Copy() method.



Unbounded Type Parameters



If you create generics data structures or classes, like MyList in Example 3, there are no
restrictions on what type the parametric type you may use for the parameteric type. This
leads to some limitations, however. For example, you are not allowed to use
==, !=, or < on instances of the parametric type:




if (obj1 == obj2) …


The implementation of operators such as == and != are different for value types and
reference types. The behavior of the code may not be easier to understand if these were
allowed arbitrarily. Another restriction is the use of default constructor. For instance, if
you write new T(), you will get a compilation error, because not all classes have a
no-parameter constructor. What if you do want to create an object using new T(), or you
want to use operators such as == and !=? You can, but first you have to constraint the type
that can be used for the parameterized type. Let's look at how to do that.



Constraints and Their Benefits



A generic class allows you to write your class without committing to any type, yet allows
the user of your class, later on, to indicate the specific type to be used. While this
gives greater flexibility by placing some constraints on the types that may be used for
the parameterized type, you gain some control in writing your class. Let's look at an example:



Example 5. The need for constraints: code that will not compile




public static T Max(T op1, T op2)
{
if (op1.CompareTo(op2) <>


The code in Example 5 will produce a compilation error:




Error 1 'T' does not contain a definition for 'CompareTo'


Assume I need the type to support the CompareTo() method. I can specify
this by using the constraint that the type specified for the parameterized type must implement the
IComparable interface. Example 6 has the code:



Example 6. Specifying a constraint




public static T Max(T op1, T op2) where T : IComparable
{
if (op1.CompareTo(op2) <>


In Example 6, I have specified the constraint that the type used for
parameterized type must inherit from (implement) IComparable.
The following constraints may be used:




where T : struct type must be a value type (a struct)
where T : class type must be reference type (a class)
where T : new() type must have a no-parameter constructor
where T : class_name type may be either class_name or one of its
sub-classes (or is below class_name
in the inheritance hierarchy)
where T : interface_name type must implement the specified interface


You may specify a combination of constraints, as in: where T : IComparable, new().
This says that the type for the parameterized type must implement the
IComparable interface and must have a no-parameter constructor.



Inheritance and Generics



A generic class that uses parameterized types, like MyClass1, is called
an open-constructed generic. A generic class that uses no parameterized types,
like MyClass1, is called a closed-constructed generic.



You may derive from a closed-constructed generic; that is, you may inherit a class
named MyClass2 from another class named MyClass1, as in:




public class MyClass2 : MyClass1


You may derive from an open-constructed generic, provided the type is parameterized.
For example:




public class MyClass2 : MyClass2


is valid, but




public class MyClass2 : MyClass2


is not valid, where Y is a parameterized type. Non-generic classes may derive from closed-constructed
generic classes, but not from open-constructed generic classes. That is,




public class MyClass : MyClass1


is valid, but




public class MyClass : MyClass1


is not.


Generics' Limitations

We have seen the power of generics so far in this article. Are there any limitations? There is one significant limitation, which I hope Microsoft addresses. In expressing constraints, we can specify that the parameter type must inherit from a class. How about specifying that the parameter must be a base class of some class? Why do we need that?

In Example 4, I showed you a Copy() method that copied contents of a source List to a destination list. I can use it as follows:

List appleList1 = new List(); List appleList2 = new List(); … Copy(appleList1, appleList2);

However, what if I want to copy apples from one list into a list of Fruits (where Apple inherits from Fruit). Most certainly, a list of Fruits can hold Apples. So I want to write:

List appleList1 = new List(); List fruitsList2 = new List(); … Copy(appleList1, fruitsList2);

This will not compile. You will get an error:

Error 1 The type arguments for method 'TestApp.Program.Copy(System.Collections.Generic.List, System.Collections.Generic.List)' cannot be inferred from the usage.

The compiler, based on the call arguments, is not able to decide what T should be. What I really want to say is that the Copy should accept a List of some type as the first parameter, and a ListList of its base type as the second parameter. of the same type or a

Even though there is no way to say that a type must be a base type of another, you can get around this limitation by still using the constraints. Here is how:

public static void Copy(List source, List destination) where T : E

Here I have specified that the type T must be the same type as, or a sub-type of, E. We got lucky with this. Why? Both T and E are being defined here. We were able to specify the constraint (though the C# specification discourages using E to define the constraint of T when E is being defined as well).

Consider the following example, however:

public class MyList { public void CopyTo(MyList destination) { //… } }

I should be able to call CopyTo:

MyList appleList = new MyList(); MyList appleList2 = new MyList(); //… appleList.CopyTo(appleList2);

I must also be able to do this:

MyList appleList = new MyList(); MyList fruitList2 = new MyList(); //… appleList.CopyTo(fruitList2);

This, of course, will not work. How can we fix this? We need to say that the argument to CopyTo()MyList of some type or MyList of the base type of that type. However, the constraints do not allow us to specify the base type. How about the following? can be either

public void CopyTo(MyList destination) where T : E

Sorry, this does not work. It gives a compilation error that:

Error 1 'TestApp.MyList.CopyTo()' does not define type parameter 'T'

Of course, you may write the code to accept MyList of any arbitrary type and then within your code, you may verify that the type is one of acceptable type. However, this pushes the checking to runtime, losing the benefit of compile-time type safety.

Conclusion

Generics in .NET 2.0 are very powerful. They allow you to write code without committing to a particular type, yet your code can enjoy type safety. Generics are implemented in such a way as to provide good performance and avoid code bloat. While there is the drawback of constraints' inability to specify that a type must be a base type of another type, the constraints mechanism gives you the flexibility to write code with a greater degree of freedom than sticking with the least-common-denominator capability of all types.

VB6 - Disable mouse events

How to Disable mouse events in vb6



Code:
Option Explicit

Private Declare Function SetCapture Lib "user32" (ByVal hwnd As Long) As Long
Private Declare Function ReleaseCapture Lib "user32" () As Long

Private Sub Form_MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single)
If Not ((X > Text1.Left And X < Text1.Left + Text1.Width) And (Y > Text1.Top And Y < Text1.Top + Text1.Height)) Then _
ReleaseCapture
End Sub

Private Sub Text1_MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single)
SetCapture Me.hwnd
End Sub

Asp.net Questions(part2)

  1. What is an interface and what is an abstract class?

    In an interface, all methods must be abstract (must not be defined). In an abstract class, some methods can be defined. In an interface, no accessibility modifiers are allowed, whereas it is allowed in abstract classes.

  2. Session state vs. View state:

    In some cases, using view state is not feasible. The alternative for view state is session state. Session state is employed under the following situations:

    • Large amounts of data - View state tends to increase the size of both the HTML page sent to the browser and the size of form posted back. Hence session state is used.
    • Secure data - Though the view state data is encoded and may be encrypted, it is better and secure if no sensitive data is sent to the client. Thus, session state is a more secure option.
    • Problems in serializing of objects into view state - View state is efficient for a small set of data. Other types like DataSet are slower and can generate a very large view state.
  3. Can two different programming languages be mixed in a single ASPX file?

    ASP.NET's built-in parsers are used to remove code from ASPX files and create temporary files. Each parser understands only one language. Therefore mixing of languages in a single ASPX file is not possible.

  4. Is it possible to see the code that ASP.NET generates from an ASPX file?

    By enabling debugging using a <%@ Page Debug="true" %> directive in the ASPX file or a <compilation debug="true"> statement in Web.config, the generated code can be viewed. The code is stored in a CS or VB file (usually in the \%SystemRoot%\Microsoft.NET\Framework\v1.0.nnnn\Temporary ASP.NET Files).

  5. Can a custom .NET data type be used in a Web form?

    This can be achieved by placing the DLL containing the custom data type in the application root's bin directory and ASP.NET will automatically load the DLL when the type is referenced.

  6. List the event handlers that can be included in Global.asax?
    • Application start and end event handlers
    • Session start and end event handlers
    • Per-request event handlers
    • Non-deterministic event handlers
  7. Can the view state be protected from tampering?

    This can be achieved by including an @ Page directive with an EnableViewStateMac="true" attribute in each ASPX file that has to be protected. Another way is to include the <pages enableViewStateMac="true" /> statement in the Web.config file.

  8. Can the view state be encrypted?

    The view state can be encrypted by setting EnableViewStateMac to true and either modifying the <machineKey> element in Machine.config to <machineKey validation="3DES" /> or by adding the above statement to Web.config.

  9. When during the page processing cycle is ViewState available?

    The view state is available after the Init() and before the Render() methods are called during Page load.

  10. Do Web controls support Cascading Style Sheets?

    All Web controls inherit a property named CssClass from the base class System.Web.UI.WebControls.WebControl which can be used to control the properties of the web control.

  11. What namespaces are imported by default in ASPX files?

    The following namespaces are imported by default. Other namespaces must be imported manually using @ Import directives.

    • System
    • System.Collections
    • System.Collections.Specialized
    • System.Configuration
    • System.Text
    • System.Text.RegularExpressions
    • System.Web
    • System.Web.Caching
    • System.Web.Security
    • System.Web.SessionState
    • System.Web.UI
    • System.Web.UI.HtmlControls
    • System.Web.UI.WebControls
  12. What classes are needed to send e-mail from an ASP.NET application?

    The classes MailMessage and SmtpMail have to be used to send email from an ASP.NET application. MailMessage and SmtpMail are classes defined in the .NET Framework Class Library's System.Web.Mail namespace.

  13. Why do some web service classes derive from System.Web.WebServices while others do not?

    Those Web Service classes which employ objects like Application, Session, Context, Server, and User have to derive from System.Web.WebServices. If it does not use these objects, it is not necessary to be derived from it.

  14. What are VSDISCO files?

    VSDISCO files are DISCO files that enable dynamic discovery of Web Services. ASP.NET links the VSDISCO to a HTTP handler that scans the host directory and subdirectories for ASMX and DISCO files and returns a dynamically generated DISCO document. A client who requests a VSDISCO file gets back what appears to be a static DISCO document.

  15. How can files be uploaded to Web pages in ASP.NET?

    This can be done by using the HtmlInputFile class to declare an instance of an <input type="file" runat="server"/> tag. Then, a byte[] can be declared to read in the data from the input file. This can then be sent to the server.

  16. How do I create an ASPX page that periodically refreshes itself?

    The following META tag can be used as a trigger to automatically refresh the page every n seconds:

    <meta http-equiv="Refresh" content="nn">
  17. How do I initialize a TextBox whose TextMode is "password", with a password?

    The TextBox's Text property cannot be used to assign a value to a password field. Instead, its Value field can be used for that purpose.

    <asp:TextBox Value="imbatman" TextMode="Password" 
    ID="Password" RunAt="server" />
  18. Why does the control's PostedFile property always show null when using HtmlInputFile control to upload files to a Web server?

    This occurs when an enctype="multipart/form-data" attribute is missing in the <form> tag.

  19. How can the focus be set to a specific control when a Web form loads?

    This can be achieved by using client-side script:

    document.forms[0].TextBox1.focus ()

    The above code will set the focus to a TextBox named TextBox1 when the page loads.

  20. How does System.Web.UI.Page's IsPostBack property work?

    IsPostBack checks to see whether the HTTP request is accompanied by postback data containing a __VIEWSTATE or __EVENTTARGET parameter. If there are none, then it is not a postback.

  21. What is WSDL?

    WSDL is an XML format for describing network services as a set of endpoints operating on messages containing either document-oriented or procedure-oriented information. The operations and messages are described abstractly, and then bound to a concrete network protocol and message format to define an endpoint. Related concrete endpoints are combined into abstract endpoints (services). (Source: www.w3.org)

  22. What is UDDI?

    UDDI stands for Universal Description, Discovery, and Integration. It is like an "Yellow Pages" for Web Services. It is maintained by Microsoft, IBM, and Ariba, and is designed to provide detailed information regarding registered Web Services for all vendors. The UDDI can be queried for specific Web Services.

  23. Is it possible to generate the source code for an ASP.NET Web service from a WSDL?

    The Wsdl.exe tool (.NET Framework SDK) can be used to generate source code for an ASP.NET web service with its WSDL link.

    Example: wsdl /server http://api.google.com/GoogleSearch.wsdl.

  24. Why do uploads fail while using an ASP.NET file upload control to upload large files?

    ASP.NET limits the size of file uploads for security purposes. The default size is 4 MB. This can be changed by modifying the maxRequestLength attribute of Machine.config's <httpRuntime> element.

  25. Describe the difference between inline and code behind.

    Inline code is written along side the HTML in a page. Code-behind is code written in a separate file and referenced by the .aspx page.

  26. Describe the role of inetinfo.exe, aspnet_isapi.dll andaspnet_wp.exe in the page loading process.

    inetinfo.exe is theMicrosoft IIS server running, handling ASP.NET requests among other things.When an ASP.NET request is received (usually a file with .aspx extension), the ISAPI filter aspnet_isapi.dll takes care of it by passing the request tothe actual worker process aspnet_wp.exe.

  27. Can you explain the difference between an ADO.NET Dataset and an ADO Recordset?

    Valid answers are:

    • A DataSet can represent an entire relational database in memory, complete with tables, relations, and views.
    • A DataSet is designed to work without any continuing connection to the original data source.
    • Data in a DataSet is bulk-loaded, rather than being loaded on demand.
    • There's no concept of cursor types in a DataSet.
    • DataSets have no current record pointer You can use For Each loops to move through the data.
    • You can store many edits in a DataSet, and write them to the original data source in a single operation.
    • Though the DataSet is universal, other objects in ADO.NET come in different versions for different data sources.
  28. What's a bubbled event?

    When you have a complex control, like DataGrid, writing an event processing routine for each object (cell, button, row, etc.) is quite tedious. The controls can bubble up their eventhandlers, allowing the main DataGrid event handler to take care of its constituents.

  29. What data types do the RangeValidator control support?

    Integer, String, and Date.

  30. Explain what a diffgram is, and a good use for one?

    The DiffGram is one of the two XML formats that you can use to render DataSet object contents to XML. A good use is reading database data to an XML file to be sent to a Web Service.

  31. What is the transport protocol you use to call a Web service?

    SOAP (Simple Object Access Protocol) is the preferred protocol.

  32. What is ViewState?

    ViewState allows the state of objects (serializable) to be stored in a hidden field on the page. ViewState is transported to the client and back to the server, and is not stored on the server or any other external source. ViewState is used the retain the state of server-side objects between postabacks.

  33. What does the "EnableViewState" property do? Why would I want it on or off?

    It allows the page to save the users input on a form across postbacks. It saves the server-side values for a given control into ViewState, which is stored as a hidden value on the page before sending the page to the clients browser. When the page is posted back to the server the server control is recreated with the state stored in viewstate.

  34. What are the different types of Session state management options available with ASP.NET?

    ASP.NET provides In-Process and Out-of-Process state management. In-Process stores the session in memory on the web server. This requires the a "sticky-server" (or no load-balancing) so that the user is always reconnected to the same web server. Out-of-Process Session state management stores data in an external data source. The external data source may be either a SQL Server or a State Server service. Out-of-Process state management requires that all objects stored in session are serializable.

  35. Differences Between XML and HTML?

    Anyone with a fundamental grasp of XML should be able describe some of the main differences outlined in the table below

    XML

    HTML

    User definable tags Defined set of tags designed for web display
    Content driven Format driven
    End tags required for well formed documents End tags not required
    Quotes required around attributes values Quotes not required
    Slash required in empty tags Slash not required

  36. Give a few examples of types of applications that can benefit from using XML.

    There are literally thousands of applications that can benefit from XML technologies. The point of this question is not to have the candidate rattle off a laundry list of projects that they have worked on, but, rather, to allow the candidate to explain the rationale for choosing XML by citing a few real world examples. For instance, one appropriate answer is that XML allows content management systems to store documents independently of their format, which thereby reduces data redundancy. Another answer relates to B2B exchanges or supply chain management systems. In these instances, XML provides a mechanism for multiple companies to exchange data according to an agreed upon set of rules. A third common response involves wireless applications that require WML to render data on hand held devices.

  37. What is DOM and how does it relate to XML?

    The Document Object Model (DOM) is an interface specification maintained by the W3C DOM Workgroup that defines an application independent mechanism to access, parse, or update XML data. In simple terms it is a hierarchical model that allows developers to manipulate XML documents easily Any developer that has worked extensively with XML should be able to discuss the concept and use of DOM objects freely. Additionally, it is not unreasonable to expect advanced candidates to thoroughly understand its internal workings and be able to explain how DOM differs from an event-based interface like SAX.

  38. What is SOAP and how does it relate to XML?

    The Simple Object Access Protocol (SOAP) uses XML to define a protocol for the exchange of information in distributed computing environments. SOAP consists of three components: an envelope, a set of encoding rules, and a convention for representing remote procedure calls. Unless experience with SOAP is a direct requirement for the open position, knowing the specifics of the protocol, or how it can be used in conjunction with HTTP, is not as important as identifying it as a natural application of XML.

  39. Can you walk us through the steps necessary to parse XML documents?

    Superficially, this is a fairly basic question. However, the point is not to determine whether candidates understand the concept of a parser but rather have them walk through the process of parsing XML documents step-by-step. Determining whether a non-validating or validating parser is needed, choosing the appropriate parser, and handling errors are all important aspects to this process that should be included in the candidate's response.

  40. What are possible implementations of distributed applications in .NET?

    .NET Remoting and ASP.NET Web Services. If we talk about the Framework Class Library, noteworthy classes are in System.Runtime.Remoting and System.Web.Services.

  41. What are the consideration in deciding to use .NET Remoting or ASP.NET Web Services?

    Remoting is a more efficient communication exchange when you can control both ends of the application involved in the communication process. Web Services provide an open-protocol-based exchange of informaion. Web Services are best when you need to communicate with an external organization or another (non-.NET) technology.

  42. What's a proxy of the server object in .NET Remoting?

    It's a fake copy of the server object that resides on the client side and behaves as if it was the server. It handles the communication between real server object and the client object. This process is also known as marshaling.

  43. What are remotable objects in .NET Remoting?

    Remotable objects are the objects that can be marshaled across the application domains. You can marshal by value, where a deep copy of the object is created and then passed to the receiver. You can also marshal by reference, where just a reference to an existing object is passed.

  44. What are channels in .NET Remoting?

    Channels represent the objects that transfer the other serialized objects from one application domain to another and from one computer to another, as well as one process to another on the same box. A channel must exist before an object can be transferred.

  45. What security measures exist for .NET Remoting in System.Runtime.Remoting?

    None. Security should be taken care of at the application level. Cryptography and other security techniques can be applied at application or server level.

  46. What is a formatter?

    A formatter is an object that is responsible for encoding and serializing data into messages on one end, and deserializing and decoding messages into data on the other end.

  47. Choosing between HTTP and TCP for protocols and Binary and SOAP for formatters, what are the trade-offs?

    Binary over TCP is the most effiecient, SOAP over HTTP is the most interoperable.

  48. What's SingleCall activation mode used for?

    If the server object is instantiated for responding to just one single request, the request should be made in SingleCall mode.

  49. What's Singleton activation mode?

    A single object is instantiated regardless of the number of clients accessing it. Lifetime of this object is determined by lifetime lease.

  50. How do you define the lease of the object?

    By implementing ILease interface when writing the class code.

  51. Can you configure a .NET Remoting object via XML file?

    Yes, via machine.config and application level .config file (or web.config in ASP.NET). Application-level XML settings take precedence over machine.config.

  52. How can you automatically generate interface for the remotable object in .NET with Microsoft tools?

    Use the Soapsuds tool.

Asp.net Questions(part1)

  1. What do I need to create and run an ASP.NET application?
  • Windows 2000, Windows Server 2003 or Windows XP.
  • ASP.NET, which can be either the redistributable (included in the .NET SDK) or Visual Studio .NET.
  1. Where can I download the .NET SDK?

    .NET SDK can be obtained here.

    (You have to install the Microsoft .NET Framework Version 1.1 Redistributable Package before installing the .NET SDK.)

  2. Are there any free IDEs for the .NET SDK?
    • Microsoft provides Visual Studio 2005 Express Edition Beta for free. Of particular interest to the ASP.NET developers would be the Visual Web Developer 2005 Express Edition Beta 2 available as a free download.
    • The ASP.NET Web Matrix Project (supported by Microsoft) is a free IDE for developing ASP.NET applications and is available here.
    • There is also a free open-source UNIX version of the Microsoft .NET development platform called Mono available for download here.
    • Another increasingly popular Open Source Development Environment for .NET is the #develop (short for SharpDevelop) available for download here.
  3. When was ASP.NET released?

    ASP.NET is a part of the .NET framework which was released as a software platform in 2002.

  4. Is a new version coming up?

    ASP.NET 2.0, Visual Studio 2005 (Whidbey), Visual Web Developer 2005 Express Edition are the next releases of Microsoft's Web platform and tools. They have already been released as Beta versions. They are scheduled to be released in the week of November 7, 2005.

  5. Explain Namespace.

    Namespaces are logical groupings of names used within a program. There may be multiple namespaces in a single application code, grouped based on the identifiers' use. The name of any given identifier must appear only once in its namespace.

  6. List the types of Authentication supported by ASP.NET.
    • Windows (default)
    • Forms
    • Passport
    • None (Security disabled)
  7. What is CLR?

    Common Language Runtime (CLR) is a run-time environment that manages the execution of .NET code and provides services like memory management, debugging, security, etc. The CLR is also known as Virtual Execution System (VES).

  8. What is CLI?

    The CLI is a set of specifications for a runtime environment, including a common type system, base class library, and a machine-independent intermediate code known as the Common Intermediate Language (CIL). (Source: Wikipedia.)

  9. List the various stages of Page-Load lifecycle.
    • Init()
    • Load()
    • PreRender()
    • Unload()
  10. Explain Assembly and Manifest.

    An assembly is a collection of one or more files and one of them (DLL or EXE) contains a special metadata called Assembly Manifest. The manifest is stored as binary data and contains details like versioning requirements for the assembly, the author, security permissions, and list of files forming the assembly. An assembly is created whenever a DLL is built. The manifest can be viewed programmatically by making use of classes from the System.Reflection namespace. The tool Intermediate Language Disassembler (ILDASM) can be used for this purpose. It can be launched from the command prompt or via Start> Run.

  11. What is Shadow Copy?

    In order to replace a COM component on a live web server, it was necessary to stop the entire website, copy the new files and then restart the website. This is not feasible for the web servers that need to be always running. .NET components are different. They can be overwritten at any time using a mechanism called Shadow Copy. It prevents the Portable Executable (PE) files like DLLs and EXEs from being locked. Whenever new versions of the PEs are released, they are automatically detected by the CLR and the changed components will be automatically loaded. They will be used to process all new requests not currently executing, while the older version still runs the currently executing requests. By bleeding out the older version, the update is completed.

  12. What is DLL Hell?

    DLL hell is the problem that occurs when an installation of a newer application might break or hinder other applications as newer DLLs are copied into the system and the older applications do not support or are not compatible with them. .NET overcomes this problem by supporting multiple versions of an assembly at any given time. This is also called side-by-side component versioning.

  13. Explain Web Services.

    Web services are programmable business logic components that provide access to functionality through the Internet. Standard protocols like HTTP can be used to access them. Web services are based on the Simple Object Access Protocol (SOAP), which is an application of XML. Web services are given the .asmx extension.

  14. Explain Windows Forms.

    Windows Forms is employed for developing Windows GUI applications. It is a class library that gives developers access to Windows Common Controls with rich functionality. It is a common GUI library for all the languages supported by the .NET Framework.

  15. What is Postback?

    When an action occurs (like button click), the page containing all the controls within the <FORM... > tag performs an HTTP POST, while having itself as the target URL. This is called Postback.

  16. 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. 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. Since the code is included in the HTML page, anyone can see the code by viewing the page source. It also poses as a possible security hazard for the client computer.

  17. Enumerate the types of Directives.
    • @ Page directive
    • @ Import directive
    • @ Implements directive
    • @ Register directive
    • @ Assembly directive
    • @ OutputCache directive
    • @ Reference directive
  18. What is Code-Behind?

    Code-Behind is a concept where the contents of a page are in one file and the server-side code is in another. This allows different people to work on the same page at the same time and also allows either part of the page to be easily redesigned, with no changes required in the other. An Inherits attribute is added to the @ Page directive to specify the location of the Code-Behind file to the ASP.NET page.

  19. Describe the difference between inline and code behind.

    Inline code is written along side the HTML in a page. There is no separate distinction between design code and logic code. Code-behind is code written in a separate file and referenced by the .aspx page.

  20. List the ASP.NET validation controls?
    • RequiredFieldValidator
    • RangeValidator
    • CompareValidator
    • RegularExpressionValidator
    • CustomValidator
    • ValidationSummary
  21. What is Data Binding?

    Data binding is a way used to connect values from a collection of data (e.g. DataSet) to the controls on a web form. The values from the dataset are automatically displayed in the controls without having to write separate code to display them.

  22. Describe Paging in ASP.NET.

    The DataGrid control in ASP.NET enables easy paging of the data. The AllowPaging property of the DataGrid can be set to True to perform paging. ASP.NET automatically performs paging and provides the hyperlinks to the other pages in different styles, based on the property that has been set for PagerStyle.Mode.

  23. Should user input data validation occur server-side or client-side? Why?

    All user input data validation should occur on the server and minimally on the client-side, though it is a good way to reduce server load and network traffic because we can ensure that only data of the appropriate type is submitted from the form. It is totally insecure. The user can view the code used for validation and create a workaround for it. Secondly, the URL of the page that handles the data is freely visible in the original form page. This will allow unscrupulous users to send data from their own forms to your application. Client-side validation can sometimes be performed where deemed appropriate and feasible to provide a richer, more responsive experience for the user.

  24. What is the difference between Server.Transfer and Response.Redirect?
    • Response.Redirect: This tells the browser that the requested page can be found at a new location. The browser then initiates another request to the new page loading its contents in the browser. This results in two requests by the browser.
    • Server.Transfer: It transfers execution from the first page to the second page on the server. As far as the browser client is concerned, it made one request and the initial page is the one responding with content. The benefit of this approach is one less round trip to the server from the client browser. Also, any posted form variables and query string parameters are available to the second page as well.

Uncommon C#.NET Keywords

Uncommon C#.NET Keywords

Virtual Functions

New and Override Methods

a.cs

class zzz

{

public static void Main()

{

yyy a = new yyy();

xxx b = new xxx();

yyy c = new xxx();

a.abc();a.pqr();a.xyz();

b.abc();b.pqr();b.xyz();

c.abc();c.pqr();c.xyz();

}

}

class yyy

{

public void abc()

{

System.Console.WriteLine(“yyy abc”);

}

public void pqr()

{

System.Console.WriteLine(“yyy pqr”);

}

public void xyz()

{

System.Console.WriteLine(“yyy xyz”);

}

}

class xxx : yyy

{

public void abc()

{

System.Console.WriteLine(“xxx abc”);

}

public void pqr()

{

System.Console.WriteLine(“xxx pqr”);

}

public void xyz()

{

System.Console.WriteLine(“xxx xyz”);

}

}

Compiler Warning

a.cs(30,13): warning CS0108: The keyword new is required on 'xxx.abc()' because it hides inherited member 'yyy.abc()'

a.cs(34,13): warning CS0108: The keyword new is required on 'xxx.pqr()' because it hides inherited member 'yyy.pqr()'

a.cs(38,13): warning CS0108: The keyword new is required on 'xxx.xyz()' because it hides inherited member 'yyy.xyz()'

Output

yyy abc

yyy pqr

yyy xyz

xxx abc

xxx pqr

xxx xyz

yyy abc

yyy pqr

yyy xyz

Class xxx derives from class yyy. That makes xxx the derived class and yyy the base class. The class xxx comprises yyy and more. Thus can we not conclude, albeit in broken English that an object that looks like xxx is bigger than one that looks like yyy. In C#, you can equate a smaller object to a bigger object as stated earlier.

Lets take the case of object a. It looks like yyy and initialized by creating an object that also looks like yyy. When we call the functions abc and pqr and xyz through the object a obviously it will call them from yyy.

Object b looks like xxx, the derived class. It is initialized to an object that looks like xxx. When we call abc, pqr and xyz through b, it calls abc, pqr and xyz from xxx.

Object c again looks like yyy but it is now initialized to an object that looks like xxx which does not give an error as explained earlier. However there is no change at all in the output and the behavior is identical to that of object a. Hence initializing it to an object that looks like yyy or xxx does not seem to matter.

a.cs

class zzz

{

public static void Main()

{

yyy a = new yyy();

xxx b = new xxx();

yyy c = new xxx();

a.abc();a.pqr();a.xyz();

b.abc();b.pqr();b.xyz();

c.abc();c.pqr();c.xyz();

}

}

class yyy

{

public void abc()

{

System.Console.WriteLine(“yyy abc”);

}

public void pqr()

{

System.Console.WriteLine(“yyy pqr”);

}

public void xyz()

{

System.Console.WriteLine(“yyy xyz”);

}

}

class xxx : yyy

{

public override void abc()

{

System.Console.WriteLine(“xxx abc”);

}

public new void pqr()

{

System.Console.WriteLine(“xxx pqr”);

}

public void xyz()

{

System.Console.WriteLine(“xxx xyz”);

}

}

Compiler Error

a.cs(30,22): error CS0506: ‘xxx.abc()’ : cannot override inherited member ‘yyy.abc()’ because it is not marked virtual, abstract, or override

We get an error because we have added two new modifiers, new and override to the functions. The error says to add the modifier virtual to the functions in the base class.

a.cs

class zzz

{

public static void Main()

{

yyy a = new yyy();

xxx b = new xxx();

yyy c = new xxx();

a.abc();a.pqr();a.xyz();

b.abc();b.pqr();b.xyz();

c.abc();c.pqr();c.xyz();

}

}

class yyy

{

public virtual void abc()

{

System.Console.WriteLine(“yyy abc”);

}

public virtual void pqr()

{

System.Console.WriteLine(“yyy pqr”);

}

public virtual void xyz()

{

System.Console.WriteLine(“yyy xyz”);

}

}

class xxx : yyy

{

public override void abc()

{

System.Console.WriteLine(“xxx abc”);

}

public new void pqr()

{

System.Console.WriteLine(“xxx pqr”);

}

public void xyz()

{

System.Console.WriteLine(“xxx xyz”);

}

}

Output

yyy abc

yyy pqr

yyy xyz

xxx abc

xxx pqr

xxx xyz

xxx abc

yyy pqr

yyy xyz

There is a single subtle change in the workings of the objects c only and not a and b. Adding the virtual modifier has made all the difference. The difference is in the object c. c looks like the base class yyy but is initialized to an object that looks like the derived class xxx. C# remembers this fact. When we execute c.abc(), C# remembers that object c was initialized by a xxx object and hence it first goes to class xxx. Here the function has a modifier override which in English means, forget about the data type of c which is yyy, call abc from xxx as it overrides the abc of the base class. The override modifier is needed as the derived class functions will get first priority and be called. We mean to override the abc of the base class. We are telling C# that this abc is similar to the abc of the base class.

New has the exactly the opposite meaning. The function pqr has the new modifier. C.pqr() calls pqr from yyy and not xxx. New means that the function pqr is a new function and it has absolutely nothing to do with the pqr in the base class. It may have the same name pqr as in the base class, but that is only a coincidence. As c looks like yyy, the pqr of yyy gets called even though there is a pqr in xxx. When we do not write any modifier, then it is assumed that we wrote new. Thus every time we write a function, C# assumes it has nothing to do with the base class. These modifiers can only be used if the function in the base class is a virtual function. To us virtual means that the base class is granting us permission to call the function from the derived class and not the base class. We have however one caveat, we have to add the modifier override if our derived class function has to be called.

a.cs

class zzz

{

public static void Main()

{

yyy a = new xxx();

yyy b = new vvv();

xxx c = new vvv();

a.abc();a.pqr();a.xyz();

b.abc();b.pqr();b.xyz();

c.abc();c.pqr();c.xyz();

}

}

class yyy

{

public void abc()

{

System.Console.WriteLine(“yyy abc”);

}

public virtual void pqr()

{

System.Console.WriteLine(“yyy pqr”);

}

public virtual void xyz()

{

System.Console.WriteLine(“yyy xyz”);

}

}

class xxx : yyy

{

public virtual void abc()

{

System.Console.WriteLine(“xxx abc”);

}

public new void pqr()

{

System.Console.WriteLine(“xxx pqr”);

}

public override void xyz()

{

System.Console.WriteLine(“xxx xyz”);

}

}

class vvv : xxx

{

public override void abc()

{

System.Console.WriteLine(“vvv abc”);

}

public void xyz()

{

System.Console.WriteLine(“vvv xyz”);

}

}

Output

yyy abc

yyy pqr

xxx xyz

yyy abc

yyy pqr

xxx xyz

vvv abc

xxx pqr

xxx xyz

Pretty long example. To reiterate, we are allowed to initialize a base object to a derived object. The other way around will generate an error. This leads to an object of a base class being initialized to an object of the derived class. The question that now springs to mind is, which function will get called. The one from the base class or the derived class. If the base class object declared the function virtual and the derived class used the modifier override, the derived class function will get called. Otherwise the base class function will get executed. Thus for virtual functions, the data type created is decided at run time. All functions not tagged with virtual are non virtual, and the function to be called is decided at compile time, depending upon the static data type of the object. If the object is initialized to the same data type, none of the above apply. Whenever we have a mismatch, we need rules to resolve the mismatch. Thus we can land up with a situation where an object to a base class can call a function in the derived class.

The object a looks like yyy but is initialized to the derived class xxx. a.abc(), first looks into the class yyy. Here it checks whether the function abc is virtual. The answer is an emphatic no and hence everything stops and the function abc gets called from class yyy. a.pqr does the same thing, but the function now is virtual in class yyy. Thus C# looks at the class yyy, the one it was initialized to. Here pqr is flagged with the modifier new. This means that pqr is a new function which has nothing to do with the one in the base class. They only accidentally share the same name. Thus as there is no function called pqr (as it is a new pqr) in the derived class, the one from base class gets called. In the case of a.xyz(), the same steps are followed again, but in the class yyy, we meet the modifier override, which overrides the function in the base class. We are telling C# to call this function in class xxx and not the one in the base class yyy.

The object b which also looks like class yyy, is now initialized with an object that looks like vvv and not xxx like before. As abc is non virtual it gets called from yyy. In the case of function pqr, C# now looks into class vvv. Here it sees no function pqr and hence now looks into class xxx. Thus the above rules repeat and it gets called from class yyy. In the case of b.xyz, in class vvv, it is marked new by default and hence this function has nothing to do with the one in class yyy. Hence the one from vvv does not get called but the one from class yyy where it specifies override.

public override void xyz()

{

System.Console.WriteLine(“vvv xyz”);

}

If we change xyz in class vvv to the above, i.e. we change new to override, the xyz of vvv will get called.

The last object c looks like xxx but is now initialized to an object that looks like the derived class vvv. c.abc(), first looks into class xxx where it is marked as virtual. Remember abc is non virtual in class yyy but virtual in xxx. From now on, the function abc is virtual in vvv also but not in class yyy. Virtual is like water, it flows downwards not upwards. As abc is virtual, we now look into class vvv. Here it is marked override and hence abc gets called from class vvv. In the case of pqr, pqr is marked virtual in class yyy and new in xxx, but as there is no function pqr in vvv, none of the modifiers matter at all. Thus it gets called from class xxx. Lastly for function xyz, in class vvv it is marked new. Hence it has no connection with the xyz in class xxx and thus function xyz gets called from xxx and not yyy.

a.cs

class zzz

{

public static void Main()

{

}

}

class yyy

{

public virtual void pqr() {}

}

class xxx : yyy

{

public new void pqr() {}

}

class vvv : xxx

{

public override void pqr() { }

}

Compiler Error

a.cs(17,22): error CS0506: ‘vvv.pqr()’ : cannot override inherited member ‘xxx.pqr()’ because it is not marked virtual, abstract, or override

We get an error as the function pqr in class xxx is marked new. This means that it hides the pqr of class yyy. Form the viewpoint of class vvv, xxx does not supply a function called pqr. The pqr in class xxx has nothing to do with the pqr in yyy. This means that the function pqr of xxx does not inherit the virtual modifier from the function pqr of class yyy. This is what the compiler is complaining about. As the function pqr in xxx has no virtual modifier, in vvv we cannot use the modifier override. You can, however, use the modifier new and remove the warning.

a.cs

class zzz

{

public static void Main()

{

yyy a = new vvv();

a.pqr();

xxx b = new vvv();

b.pqr();

}

}

class yyy

{

public virtual void pqr()

{

System.Console.WriteLine(“yyy pqr”);

}

}

class xxx : yyy

{

public virtual new void pqr()

{

System.Console.WriteLine(“xxx pqr”);

}

}

class vvv : xxx

{

public override void pqr()

{

System.Console.WriteLine(“vvv pqr”);

}

}

Output

yyy pqr

vvv pqr

and if we remove the override modifier from pqr in vvv we get

public void pqr()

{

System.Console.WriteLine(“vvv pqr”);

}

Output

yyy pqr

xxx pqr

That’s the problem with virtual functions. We call them the cause of migraine. The answers are always different from what you expect. Object a looks like a yyy but is initialized to the derived class vvv. As pqr is virtual, C# now looks into class vvv. However before looking into the class, it realizes that in class xxx, pqr is new. This cuts of all connection with the pqr in yyy. Thus the word new is preceded with virtual, otherwise the override modifier would give us an error in class vvv. As pqr in class xxx is new function, having nothing to do with the class yyy, class vvv inherits a new which also has nothing to do with the class yyy. The pqr in class vvv is related to the pqr of class xxx and not of class yyy. Thus the pqr of class yyy gets called.

In the second case object b looks like class xxx now but is initialized to an object of class vvv. C# first looks at class xxx. Here pqr is new and virtual, which makes it a unique function pqr. Unfortunately, the pqr in vvv has the override modifier which sees to it that the pqr of vvv hides the pqr of xxx. This calls the pqr of vvv instead. If we remove the override modifier from pqr in class vvv, the default is new, that cuts off the umbilical cord from the pqr of xxx. Thus, as it is, a new function, the pqr of xxx gets called.

A virtual function cannot be marked by the modifiers static, abstract or override. A non virtual function is said to be invariant. This means that the same function gets called always, irrespective of whether one exists in the base class or derived class. In a virtual function the run-time type of the instance decides on which function to be called and not the compile-time type as is in the case of non virtual functions. For a virtual function there exists a most derived implementation which gets always gets called.

a.cs

class zzz

{

public static void Main()

{

yyy a = new vvv();

xxx b = new vvv();

www c = new vvv();

vvv d = new vvv();

a.pqr();b.pqr();c.pqr();d.pqr();

}

}

class yyy

{

public virtual void pqr()

{

System.Console.WriteLine(“yyy pqr”);

}

}

class xxx : yyy

{

public override void pqr()

{

System.Console.WriteLine(“xxx pqr”);

}

}

class www : xxx

{

public virtual new void pqr()

{

System.Console.WriteLine(“www pqr”);

}

}

class vvv : www

{

public override void pqr()

{

System.Console.WriteLine(“vvv pqr”);

}

}

Output

xxx pqr

xxx pqr

vvv pqr

vvv pqr

One last explanation of virtual with a slightly more complex example involving 4 classes.

The first line in Output, xxx pqr, is the result of the statement a.pqr();. We have the function pqr as virtual in class yyy. Hence, when using new, we now proceed to class xxx and not vvv as explained earlier. Here, pqr has an override and C# knows that class www inherits this function pqr. In class www, as it is marked as new, C# will now backtrack and not proceed further to class vvv. Hence the function pqr gets called from class xxx as shown in the output.

public override void pqr()

{

System.Console.WriteLine(“www pqr”);

}

If we change the function pqr in class www to override, then C# will proceed to class vvv and call the pqr of class vvv as it overrides the pqr of www. Remove the override from pqr in class vvv and the function will get called from class www as the default is new.

For object b, everything remains the same as object a, because it overrides the pqr of class yyy.

Restoring back the defaults, lets look at the third line. Object c looks like www. In class www, pqr is a new and hence it has nothing to do with the earlier pqr functions. In class vvv, we are overriding the pqr of class www and hence the pqr of vvv gets called. Remove the override and then it will get called from class www. The object d thankfully follows none of the above rules as the left and the right of the equal to sign are the same data types.

An override method is a method that has the override modifier included on it. This introduces a new implementation of a method. You cannot use the modifiers new, static or virtual along with override. However abstract is permitted.

a.cs

class zzz

{

public static void Main()

{

yyy a = new xxx();

a.pqr();

yyy b = new www();

b.pqr();

}

}

class yyy

{

public virtual void pqr()

{

System.Console.WriteLine(“yyy pqr”);

}

}

class xxx : yyy

{

public override void pqr()

{

base.pqr();

System.Console.WriteLine(“xxx pqr”);

}

}

class www : xxx

{

public override void pqr()

{

base.pqr();

System.Console.WriteLine(“www pqr”);

}

}

Output

yyy pqr

xxx pqr

yyy pqr

xxx pqr

www pqr

Using the keyword base, we can access the base class functions. Here whether pqr is virtual or not, it is treated as non virtual by the keyword base. Thus the base class pqr will always be called. The object a knows that pqr is virtual. When it goes to yyy, it sees base.abc and hence it calls the pqr of yyy. In the second case, it first goes to class vvv, here it calls the base.abc, i.e. the function pqr of class xxx, which in turn calls function pqr in class yyy.

a.cs

class zzz

{

public static void Main()

{

yyy a = new xxx();

a.pqr();

}

}

class yyy

{

public virtual void pqr()

{

System.Console.WriteLine(“yyy pqr”);

}

}

class xxx : yyy

{

public override void pqr()

{

((yyy)this).pqr();

System.Console.WriteLine(“xxx pqr”);

}

}

Output

Unhandled Exception: StackOverflowException.

No amount of casting will stop the infinite loop. Thus even though this is being cast to a yyy, it will always call pqr from xxx and not yyy. Hence you see no output

a.cs

class zzz

{

public static void Main()

{

yyy a = new www();

xxx b = new www();

a.pqr();a.xyz();

b.pqr();b.xyz();

}

}

class yyy

{

public virtual void pqr()

{

System.Console.WriteLine(“yyy pqr”);

}

public virtual void xyz()

{

System.Console.WriteLine(“yyy xyz”);

}

}

class xxx : yyy

{

private new void pqr()

{

System.Console.WriteLine(“xxx pqr”);

}

public new void xyz()

{

System.Console.WriteLine(“xxx xyz”);

}

}

class www : xxx

{

public override void pqr()

{

System.Console.WriteLine(“www pqr”);

}

public void xyz()

{

System.Console.WriteLine(“www xyz”);

}

}

Output

www pqr

yyy xyz

www pqr

xxx xyz

More virtual functions, more complications in life. Let us embark on a thousand mile journey with a single step.

When we have a statement a.pqr, C# starts at the class yyy as usual, sees virtual, then goes to class xxx. Here pqr is private and hence its scope is limited to class xxx. The modifier new is thus ignored. C# now goes to class www where the pqr overrides the pqr of class yyy and thus we see www pqr. If we remove the override modifier from function pqr in class www, as it is a new function, it will now be called from class yyy. a.xyz calls pqr from yyy due to the explanation given many times before i.e. they are all news.

b.pqr knows that pqr in class xxx is private. The scope of this pqr does not extend to class www, the derived class. As the pqr in class www overrides the pqr of class xxx, the one from class www gets called as it overrides the one from the base class yyy. If you change the override to new, then the pqr in www is a new one and has nothing to do with the one from yyy. This calls pqr from the base class yyy.

b.xyz calls it from class xxx. This has already been explained at least a trillion times earlier.

Abstract Classes

a.cs

public class zzz

{

public static void Main()

{

new aaa();

}

}

abstract class aaa {

}

Compiler Error

a.cs(5,1): error CS0144: Cannot create an instance of the abstract class or interface ‘aaa’

The keyword abstract can be written before a class. It is called a class modifier. An abstract class cannot be instantiated by the keyword new. We cannot create an object that looks like aaa. Thus we cannot use the class and for all practical purposes the class is useless to us.

a.cs

public class zzz

{

public static void Main()

{

new aaa();

}

}

abstract class aaa

{

public int i;

public void abc()

{

}

}

The error remains the same. Since we have used the modifier abstract in front of the class we cannot use new. Had we removed the modifier abstract, all would be fine. This program is to show that an abstract class can contain variables and functions.

a.cs

public class zzz

{

public static void Main()

{

new bbb();

}

}

abstract class aaa

{

public int i;

public void abc()

{

}

}

class bbb : aaa

{

}

We can derive a class bbb from an abstractc class aaa. Thus creating an object that looks like bbb does not give us any error. We cannot yet use aaa directly.

a.cs

public class zzz

{

public static void Main()

{

new bbb();

}

}

abstract class aaa

{

public void pqr();

public int i;

public void abc()

{

}

}

class bbb : aaa

{

}

Compiler Error

a.cs(10,13): error CS0501: ‘aaa.pqr()’ must declare a body because it is not marked abstract or extern

In a abstract class we have added a function prototype. An extern or abstract function implies that the actual definition or code is created somewhere else. A function prototype in a abstract class must also be declared abstract as per the rules of C#.

a.cs

public class zzz

{

public static void Main()

{

new bbb();

}

}

abstract class aaa

{

abstract public void pqr();

public int i;

public void abc()

{

}

}

class bbb : aaa

{

}

Compiler Error

a.cs(16,7): error CS0534: ‘bbb’ does not implement inherited abstract member ‘aaa.pqr()’

After declaring pqr abstract in aaa, we get another error. We are not allowed to create objects that look like bbb because it is derived from aaa, an abstract class which has one abstract function. We have to implement this abstract function pqr in bbb .

a.cs

public class zzz

{

public static void Main()

{

new bbb();

}

}

abstract class aaa

{

abstract public void pqr();

public int i;

public void abc()

{

}

}

class bbb : aaa

{

public void pqr()

{

}

}

Compiler Warning

a.cs(18,13): warning CS0114: ‘bbb.pqr()’ hides inherited member ‘aaa.pqr()’. To make the current method override that implementation, add the override keyword. Otherwise add the new keyword.

Compiler Error

a.cs(16,7): error CS0534: ‘bbb’ does not implement inherited abstract member ‘aaa.pqr()’

Now we are really lost. The error clearly says that both classes aaa and bbb have a similar function called pqr. Whenever a class (bbb) derives from another class (aaa) and they both have a function with the same name, an error results. The only way out is for the derived class bbb to explicitly add a keyword override to the function definition. This tells the compiler that we know that the base class has a function of the same name and we want the pqr of bbb to be called, not aaa’s . It is more of a caution exercised by the compiler so that you do not inadvertently override functions of the base class. C# has a large number of such cautions that make you think.

a.cs

public class zzz

{

public static void Main()

{

new bbb();

}

}

abstract class aaa

{

abstract public void pqr();

public int i;

public void abc()

{

}

}

class bbb : aaa

{

public override void pqr()

{

}

}

The warning vanishes after using the keyword override.

a.cs

public class zzz

{

public static void Main()

{

new bbb();

}

}

abstract class aaa

{

abstract public void pqr();

public int i;

public void abc()

{

}

}

class bbb : aaa

{

public override int pqr()

{

}

}

Compiler Error

a.cs(18,21): error CS0508: ‘bbb.pqr()’: cannot change return type when overriding inherited member ‘aaa.pqr()’

When you are overriding an abstract function from a derived class, you cannot change the parameters passed to it or the return type. If the abstract class has 5 functions, the class derived from it should also implement the same 5 functions without changing return type and/or parameters passed to it.

a.cs

public class zzz

{

public static void Main()

{

new bbb();

}

}

abstract class aaa

{

abstract public void pqr();

abstract public void pqr1();

abstract public void pqr2();

public int i;

public void abc()

{

}

}

class bbb : aaa

{

public override void pqr()

{

}

}

Compiler Error

a.cs(18,7): error CS0534: ‘bbb’ does not implement inherited abstract member ‘aaa.pqr1()’

a.cs(18,7): error CS0534: ‘bbb’ does not implement inherited abstract member ‘aaa.pqr2()’

The error goes away if we implement functions pqr1 and pqr2 in bbb.

An abstract class implies that the class is incomplete and cannot be directly used. It can only be used as a base class for other classes to derive from. Hence we get a error if we use new on an abstract class. If we do not initialize a variable in an abstract class, it will have a value of 0 which is what the compiler kept warning us about. We can initialize i to any value we want. The variables have the same use and meaning in an abstract class like any other class. Whenever a class is incomplete i.e. we do not have the code for certain functions, we make those functions abstract and the class abstract . This enables us to compile the class without errors. Other classes can then derive from our incomplete class but they have to implement the abstract i.e. our incomplete functions. Abstract thus enables us to write code for part of the class and allows the others to complete the rest of the code.

a.cs

public class zzz

{

public static void Main()

{

}

}

class aaa

{

abstract public void pqr();

public int i = 20;

public void abc()

{

}

}

Compiler Error

a.cs(9,22): error CS0513: ‘aaa.pqr()’ is abstract but it is contained in nonabstract class ‘aaa’

If a class has even one abstract function, then the class has to be declared abstract. An abstract method cannot also use the modifiers static or virtual.

Only in the abstract class can we have one abstract function. Anyone who implements from an abstract class has to write the code for its function. By default the modifier new gets added, which makes it a new/different function.

a.cs

class zzz

{

public static void Main()

{

}

}

abstract class yyy

{

public abstract void abc();

}

class xxx : yyy

{

public override void abc()

{

base.abc();

}

}

Compiler Error

a.cs(15,1): error CS0205: Cannot call an abstract base method: ‘yyy.abc()’

Like the Sting number, C# is always watching every step you take and every move you make. Like a hawk. You cannot call the function abc from the base class as it does not carry any code along with it and has been declared abstract. Common sense prevails and C# does not allow you to call a function that has no code.

a.cs

class zzz

{

public static void Main()

{

yyy a = new www();

xxx b = new www();

a.abc();b.abc();

}

}

class yyy

{

public virtual void abc()

{

System.Console.WriteLine(“yyy abc”);

}

}

abstract class xxx : yyy

{

public abstract new void abc();

}

class www : xxx

{

public override void abc()

{

System.Console.WriteLine(“www abc”);

}

}

Output

yyy abc

www abc

a.abc() will first peek into the class yyy. Here it finds function abc tagged as virtual. How many times have we repeated the above lines? Countless times. C# will then toddle over to class xxx. Here it finds to its dismay that the function abc is abstract i.e. there is no code for abc and also that it is a new function, thus severing all links with the base class. Activity stops and all hell breaks loose and the function abc from yyy gets executed. In the case of b.abc(), as the function is new, the links to the base class are broken, we have no choice but to call the function from www as it says override. We cannot replace the modifier new with the keyword override for function abc in abstract class xxx .

Compiler Error

a.cs(21,7): error CS0534: ‘www’ does not implement inherited abstract member ‘xxx.abc()’

If we replace the override keyword with new in class www, we will get an error as there is no code for the function abc. Remember the abc of yyy has nothing to do at all with that of xxx and www.

Virtual functions run slower than non virtual functions and it is obvious that an abstract class cannot be sealed.

a.cs

public class zzz

{

public static void Main()

{

}

}

sealed abstract class aaa

{

public abstract void abc();

}

Compiler Error

a.cs(7,23): error CS0502: 'aaa' cannot be both abstract and sealed

Listen to nirmaln - sakara - playlist audio songs at MusicMazaa.com