Tuesday, July 31, 2007


Mercury Diagnostics






Mercury Diagnostics™ isolates application performance problems and reduces the mean time to resolution (MTTR) of your application performance bottlenecks. It provides actionable information to resolve performance problems.





Mercury Diagnostics™ is a best-of-breed solution—for composite applications management (CAM) as well as traditional applications management—that helps you ensure 24x7 application availability and performance in production and pre-production environments to provide better service to the business. Only Mercury Diagnostics enables you to start with the end user (real users or synthetic-scripted transactions) and then drill down in context to quickly resolve a broad range of problems that can impact business availability.




Examples of these problems include:





  • End users experiencing slow performance when submitting orders.

  • Intermittent failure of online portal for order status.

  • Business-critical applications running out of memory.

  • Failure of one node on a cluster every day.



Mercury Diagnostics provides broad monitoring and deep root-cause analysis capabilities and is a true lifecycle solution that bridges the gap between organizational silos to enable effective collaboration even among diverse, dispersed teams. It provides end-to-end visibility into application performance across the lifecycle.




With Mercury Diagnostics, we can:



  • Reduce the number and duration of incidents—lowering the costs associated with problem identification and resolution.

  • Lower costs by reducing fault management efforts and hardware and software expenses for fast time to value.

  • Collaborate across team boundaries and streamline the learning curve of those responsible for maintaining J2EE, .NET, and ERP/CRM applications.




Mercury Diagnostics supports a variety of platforms and solutions including, but not limited to, the following:



  • Industry-leading J2EE application servers such as Weblogic, Websphere, Oracle, Fujitsu Interstage, TMaxSoft, ATG, and Sun One.

  • Industry-leading portal solutions such as Weblogic Portal, Websphere Portal, and SAP Enterprise Portal.

  • Industry-leading SOA platforms, packaged application technologies (SAP, Oracle), mainframe back ends (MQ Series, CICS), and enterprise databases (Oracle, SQL Server, DB2).

  • Microsoft .NET Common Language Runtime (1.1 & 2.0).

  • Industry-leading application JVMs from Sun, IBM, BEA, and HP.

  • Various open source platforms and frameworks such as JBoss, Tomcat, Struts, and Hibernate.






Integrated with Mercury LoadRunner, Mercury Business Availability Center and Mercury Performance Center




Mercury Diagnostics is integrated with Mercury Business Availability Center™ and Mercury Performance Center.




§ Mercury LoadRunner is an enterprise testing tool that predicts system behavior and employs performance monitors, called agents, which trace events along an application path to quickly isolate system bottlenecks with minimal impact to the system.


§ Mercury Business Availability center is an integrated set of software, solutions, and best practices for monitoring and managing business applications and systems.


§ Mercury Performance center is an integrated set of software, services, and best practices for automating key performance activities, including load testing, performance tuning, application diagnostics, and capacity planning.






Features and Benefits




Integration with Mercury Business Availability Center™, Mercury Performance Center™, and Mercury LoadRunner™: Mercury Diagnostics™ provides full integration with Mercury Optimization Centers to deliver a 24x7, 360-degree application performance management solution for your complex applications across the lifecycle. This integration helps you understand the end-user impact (real-users or synthetic scripted transactions) of application downtime and the readiness of applications to go live.



End-to-End Monitoring and Diagnostics for Composite Applications: Unlike other tools that work on one technology platform at a time or have different point modules for different problems, Mercury Diagnostics provides comprehensive visibility across multiple technology platforms such as JAVA, J2EE, .NET, and ERP/CRM.


Mercury Diagnostics offers best-of-breed capabilities such as:




  • Low-overhead monitoring, alerts, triage, and diagnosis of problems in heterogeneous environments (SOA/Web services /JAVA /J2EE /.NET /SAP/Oracle/MQ/CICS and other applications) across the
    lifecycle, 24x7.

  • Monitoring, alerts, triage, and diagnosis of problems with databases, including wait-time analysis for Oracle 10g.

  • SQL and method-level trending to monitor SQL and method performance over time.

  • Actionable data for development such as CPU time by method, heap dump, thread dump, exceptions, and advanced instrumentation control.

  • Advanced memory diagnostics, including allocation analysis, heap walker, and more.

  • Cross-VM instance tracing across technology stacks (J2EE, .NET, SAP R3).

  • Support for reverse proxy and role-based security built in and integrated with Mercury centers.




Cross-Team Collaboration: Mercury Diagnostics not only isolates problem areas, but also empowers the teams responsible for resolving the problem with actionable data via collaborative, role-based web dashboards.
Collaboration is key to helping solve problems and finding system errors in the shortest time to minimize impact of downtime on business availability. Mercury Diagnostics enables collaboration by providing the following capabilities:



  • Shared workspace, for incident analysis for cross-team collaboration.

  • Application grouping, quick status, user annotations, and drag-and-drop role-based views.

  • Production-ready integrated profiler for developers.

  • Automated common tasks for user guidance.




Advantages of Mercury Diagnostics


.It provides end-to-end visibility into application performance across the lifecycle.



How it works:


Mercury Diagnostics features a smart application lifecycle probe (or agent) that collects performance, availability, and diagnostics data from applications without any need for application source code modification or recompilation. It uses byte code instrumentation and industry standards for collecting system and JMX metrics. The architecture allows you to provision your application bundled with the probe through its lifecycle. It will work either standalone or integrated with Mercury's industry-leading testing and management solutions. An XML data-access layer allows you to export diagnostics data to any XML-compliant data source. The following diagram shows the high-level architecture.




Life Cycle Architecture




During a performance test, Mercury Diagnostics traces J2EE, .NET, or ERP/CRM business processes from the
client-side across all tiers of the infrastructure. The modules then break down each transaction response time into time spent in the various tiers and within individual components. You gain:










§ An intuitive, easy-to-use view of how individual tiers, components, memory, and SQL statements impact overall performance of a business process under load conditions. During or after a load test, you can not only point out to the application team that the application is not scaling, but also provide actionable data to them.


§ The ability to effectively triage and find problems with business context, enabling teams to focus on problems impacting business processes.


§ The ability to more easily find components relevant to a specific business process under test. Because J2EE and ERP/CRM applications potentially use thousands of components, this can be a challenge. Mercury Diagnostics automatically detects which components are “active” when a given transaction is executed and collects data on them for analysis. Components untouched by the business process are filtered out, enabling you to focus on getting the job done, not configuring the system.


The Call Profile Window is made up of three areas:



Ø Call Profile Graph


Ø Call Tree Table


Ø Metrics Inspector







Mercury Diagnostic Profiler




Diagnostics Profiler is part of the Mercury Diagnostics product family, which is a single-vendor lifecycle performance diagnostics solution that eliminates the need to use several different tools to analyze and diagnose application development problems. In addition, it’s simple to install and provides immediate value with diagnostics information that helps you quickly resolve performance problems.





Mercury Diagnostics Profiler features the capabilities most sought after by application owners in solving tough application problems. It enables you to collect critical diagnostics information to make applications ready for load testing and to solve problems earlier in the application lifecycle.





Diagnostics Profiler integrates into the lifecycle of load testing and problem isolation in production by sharing the same lifecycle probe as Mercury Diagnostics — our diagnostics solution for monitoring, triaging, and diagnosing application performance problems in testing and production environments. It enables you to diagnose application performance problems across the performance management lifecycle.







The Diagnostics Profiler probe uses byte code instrumentation, enabling your application to capture diagnostics data that is relevant to end users. It provides concrete information that point to the root cause of problems, arming you with actionable information. When installed, the probe captures appropriate diagnostics data and sends it to the profiler data sink. The applet-based diagnostics UI presents this data to the user in ways that can help you solve the most common application problems found in the application lifecycle.





Key Functions



Memory Diagnostics allows you to quickly identify the top fastest growing and largest collections, including the size of the collection and where in your code the collection was allocated. Mercury Diagnostics Profiler provides memory diagnostics in JAVA collections. It also allows you to take heap snapshots to obtain byte size for objects.


Exception Diagnostics allows you to quickly determine if your application is throwing exceptions and exactly what those exceptions are. Often, exceptions are “eaten” without good reason, causing significant problems under load. This feature enables you to quickly identify problem areas so you can fix them before you release to QA.



Heap Breakdown allows you to quickly get a dump of your heap to find out if and exactly which objects are leaking. This provides you with the ability to force a Garbage Collection (GC) and capture snapshots on demand or automatically when heap growth crosses a threshold.





FEATURES AND BENEFITS








  • Summary and hotspots: Identify top performance hotspots in applications.

§ Server request breakdown: Identify where time is spent.


§ Layer breakdown: Identify which layer is slow.


§ Slowest roots: Identify slowest server request or application entry points for non-web-fronted
applications.


§ Top three slowest instances: Identify outliers for intermittent problems.


§ VM heap usage: Identify memory problems/GC.


§ Collection memory leak diagnostics: Identify fastest-growing and largest size JAVA collections
including the caller and the exact line number where collection was allocated.


§ Heap breakdown with class and size information: Identify leaking object, growth trends,
instance count, and byte size for objects.


§ SQL diagnostics (slowest SQL): Identify slowest SQL query with query information.


§ Synchronization diagnostics: Identify locks with hold times.


§ Exception diagnostics (including exception traces and count): Identify exception counts
and trace information that often might go undetected.







Thursday, February 15, 2007

.Net Questions

1. What is WebService?
XML Web services are applications that provide the ability to exchange
messages in a loosely coupled environment using standard protocols such as HTTP, XML, XSD, SOAP, and WSDL.
--------------------
1. Explain the differences between Server-side and Client-side code?
The code which executes at server is called Server-Side Like Code Behind vb.net and which
is executes at client side is called client-side Code like JavaScript.
--------------------
2. What type of code (server or client) is found in a Code-Behind class?
Server Side
--------------------
3. Should validation (did the user enter a real date) occur server-side or client-side? Why?
Client Side, To save the server round trip. Readuce the Performance Over Head.
--------------------
4. What does the "EnableViewState" property do? Why would I want it on or off?
The ViewState property provides a dictionary object for retaining values between multiple requests for the same page.
This is the method that the page uses to preserve page and control property values between round trips.

Pages are destroyed and recreated with each round trip to the server; therefore page information will not exist beyond the life cycle of a single page.
If application required to keep the property value to be persisted in the server round trip then viewstate property should be turn on.
If property value is not required to be persisted in server round trip then viewstate property should be turn off, which also reduce the performance overhead.

Note : When the page is processed, the current state of the page and controls is hashed into a string and saved in the page as a hidden field.
When the page is posted back to the server, the page parses the view state string at page initialization and restores property information in the page.
--------------------
5. What is the difference between Server.Transfer and Response.Redirect? Why would I choose one over the other?
Server.Transfer method to redirect the browser to the specified page. The page transferred to should be another Web Forms page (.aspx page) in the same application.

HttpResponse.Redirect method to redirect the browser to the specified URL. Redirect method is executed by the browser and therefore results in an extra round trip between server and browser

Server.Transfer executes on the serverside and Response.redirect executs on the client side. So whenever page has to be redirected to the another page at serverside then server.transfer should be used which reduced the extra round trip to client. And if page/URL has to be transfered from client side then response.redirect should be used.

Note: Because Server.Transfer is executed on the server, the browser does not have a record of the page change. Therefore, if the user refreshes the page, unexpected results can occur.
--------------------
6. Can you give an example of when it would be appropriate to use a web service as opposed to a non-serviced .NET component
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Note :
In-Process Components :
In .NET, components built as DLLs run within the process space of the host application and share memory and processor time with their host applications. At run time, the component (which is part of the host application's assembly and is referenced by its manifest) is loaded from disk and added to the host application's process space. Because no remote procedure calls are generated to mediate communication between the component and its host, setting and reading property values, invoking methods, and responding to events raised by the component occurs very quickly.

Out-of-Process Components
An alternate architecture involves server applications that run as independent processes outside of the client application process space. These server applications usually (but not always) have an EXE file name extension. When Windows loads an out-of-process component, a separate process space is created for the component, and Windows manages the out-of-process component's resource requirements independently of the client application. Windows mediates the dialog between the server application (that is, the component) and the client (the consumer) by passing messages between them.

Differences Between Running Components In-Process vs. Out-of-Process in Visual Basic 6.0 Compared to Visual Basic .NET

There are several significant differences between in-process and out-of-process application architecture:
1. In-process applications tend to run faster because remote procedure calls are not necessary. The client application has direct access to the component without Windows mediating the dialog.
2. Out-of-process applications may, in some cases, prove to be more stable than applications built from in-process components. If an out-of-process component crashes, it does not take the consumer application with it. More often than not, if an in-process component stops running, its consumer also crashes.
3. Out-of-process components are more easily shared among a number of consumer applications. When compiled as sharable resources, Windows loads a single copy of an out-of-process component and makes it available to as many consumers as request it. Serious performance degradation can occur, however, if the component is simultaneously requested by a large number of consumers.


--------------------
7. Let's say I have an existing application written using Visual Studio 6 (VB 6, InterDev 6) and this application utilizes Windows 2000
COM+ transaction services. How would you approach migrating this application to .NET
------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Note:When a Visual Basic 6.0 application is upgraded to Visual Basic .NET, the conversion of some code is impossible due to syntactical or architectural differences. For this reason, functions in the Visual Basic 6.0 Compatibility library (Microsoft.VisualBasic.Compatibility) are used to allow the code to run in Visual Basic .NET without the need for extensive modification.
--------------------
8. Can you explain the difference between an ADO.NET Dataset and an ADO Recordset?
The DataSet, which is an in-memory cache of data retrieved from a data source, that provides a consistent relational programming model regardless of the source of the data it contains.
· 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.

Note: The ADO Recordset bundles functionality together into one object and handles much behavior implicitly. ADO.NET, on the other hand, has been designed to factor behavior into separate components and to enable you to explicitly control behavior. The following ADO.NET objects that provide the functionality of the ADO Recordset.
1.Data Reader
2.Data Set
3.Data Adapter


--------------------
9. 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.
--------------------
10. If I'm developing an application that must accomodate multiple
security levels though secure login and my ASP.NET web appplication is
spanned across three web-servers (using round-robbin load balancing)
what would be the best approach to maintain login-in state for the
users?
-- Cookies (Guess so.)
Note: Comment Required!!!!
---------------
11. What are ASP.NET Web Forms? How is this technology different than
what is available though ASP (1.0-3.0)?
------------------------------------------------------------------------------------------------



---------------
12. How does VB.NET/C# achieve polymorphism?
Inheritance based polymorphism &
Interface based polymorphism
----------------
11. Can you explain what inheritance is and an example of when you
might use it?
Inheritance is used to derived new class based on the exisiting class (base class).
Derived classes inherit, and can extend, the properties, methods, events, fields, and constants defined in the base class. Example:
1. Base Class : People.
2. Derived Class : Employee.
3. Derived Class : Worker.
-------------------
13. How would you implement inheritance using VB.NET/C#?
using "Inherits" statement.
--------------------
14. Whats an assembly


-------------------------------
15. Describe the difference between inline and code behind - which is best in a loosely coupled solution.
-------------------------------------------------------------------------------------------------------------------------------------


--------------------------
16. Explain what a diffgram is, and a good use for one
-----------------------------------------------------------------------
A DiffGram is an XML format that is used to identify current and original versions of data elements.

Good Use : DataSet uses the DiffGram format.
Where the object has to be send across the network with serializable.

Note: The DataSet uses the DiffGram format to load and persist its contents, and to serialize its contents for transport across a network connection. When a DataSet is written as a DiffGram, it populates the DiffGram with all the necessary information to accurately recreate the contents,
though not the schema, of the DataSet, including column values from both the Original and Current row versions, row error information, and row order.

When sending and retrieving a DataSet from an XML Web service, the DiffGram format is implicitly used. Additionally, when loading the contents of a DataSet from XML using the ReadXml method, or when writing the contents of a DataSet in XML using the WriteXml method, you can select that the contents be read or written as a DiffGram.

The DiffGram format is divided into three sections: the current data, the original (or "before") data, and an errors section

xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"
xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">












The name of this element, DataInstance, is used for explanation purposes in this documentation. A DataInstance element represents a DataSet or a row of a DataTable. Instead of DataInstance, the element would contain the name of the DataSet or DataTable. This block of the DiffGram format contains the current data, whether it has been modified or not. An element, or row, that has been modified is identified with the diffgr:hasChanges annotation.


This block of the DiffGram format contains the original version of a row. Elements in this block are matched to elements in the DataInstance block using the diffgr:id annotation.


This block of the DiffGram format contains error information for a particular row in the DataInstance block. Elements in this block are matched to elements in the DataInstance block using the diffgr:id annotation.
---------------------
17. Where would you use an iHTTPModule, and what are the limitations of any approach you might take in implementing one
--------------------------------------------------------------------------------------------------------

Implementing the IHttpModule interface allows you to include custom events that participate in every request made to your application.

Modules are called before and after the handler executes. Modules enable developers to intercept, participate in, or modify each individual request. Modules implement the IHttpModule interface, which is located in the System.Web namespace.


Note: HTTP modules and HTTP handlers are an integral part of the ASP.NET architecture.
While a request is being processed, each request is processed by multiple HTTP modules (for example, the authentication module and the session module) and is then processed by a single HTTP handler. After the handler has processed the request,
the request flows back through the HTTP modules

HTTP Handlers:
Handlers are used to process individual endpoint requests. Handlers enable the ASP.NET framework to process
individual HTTP URLs or groups of URL extensions within an application.
Unlike modules, only one handler is used to process a request. All handlers implement the IHttpHandler interface, which is located in the System.Web namespace. Handlers are somewhat analogous to Internet Server Application Programming Interface (ISAPI) extensions.
--------------------------------

18. What are the disadvantages of viewstate/what are the benefits
Advantage : To hold the value of page, page control or to save the values independent of control between round trips to the server.

Disadvantage : Where the control value will be retrieved from database always. At that time if viewstate property is true then system will
unnecessarly store the control value in hidden field and when page posted back it will parsed the hidden field value and assigned it to the control.
This will create performance overhead.

Note :
Each control , including page itself has a viewstate porperty , which automatically save the values of the page and of each control
just prior to rendering to the page.When the page is posted, one of the first tasks performed by page processing is to restore view state.

When the page is processed, the current state of the page and controls is hashed into a string and saved in the page as a hidden field.
When the page is posted back to the server, the page parses the view state string at page initialization and restores property information in the page.
---------------------------
19. Describe session handling in a webform, how does it work and what are the > limits
-------------------------------------------------------------------------------------------------------------------
Two way of session hanlding
1. client-side cookie : ASP.NET session object uses a client-side cookie to store an identifier. This identifier is used to locate the session across server round trips.
2. cookie less session : In cookieless session mode that initially redirects the client to a new URL containing the session ID,
and then automatically parses the session ID out of the URL.



Note :
HTTP is a stateless protocol, which means that it does not automatically indicate whether a sequence of requests is all from the same client or even whether a single browser instance is still actively viewing a page or site. As a result, building Web applications that need to maintain some cross-request state information (shopping carts, data scrolling, and so on) can be extremely challenging without additional infrastructure help.

Session state, however, does not persist across Web application boundaries. If a Web application switches to another application during execution, the session information is not available to the new application.

Each active ASP.NET session is identified and tracked using a 120-bit SessionID string containing only the ASCII characters that are allowed in URLs. SessionID values are generated using an algorithm that guarantees uniqueness so that sessions do not collide, and randomness so that a malicious user cannot use a new SessionID to calculate the SessionID of an existing session.

The SessionID strings are communicated across client-server requests either by means of an HTTP cookie or a modified URL with the SessionID string embedded, depending on how you configure the application settings.

---------------------------
20. How would you get ASP.NET running in Apache web servers - why would you even do this?
The Mono Project, as the software development effort is officially known, is primarily designed to allow Unix and Linux developers to compile and run .NET applications on their platform of choice.

Reason : low-cost web hosting.

Note:
The answer comes in the form of a free software download from Ximian, a little known company that was recently acquired by networking giant Novell.
ASP.NET applications in a low-cost environment—will inevitably be drawn to the powerful combination of Linux and Mono to provide this capability.
--------------------------------
21. Whats MSIL, and why should my developers need an appreciation of it if at all?
When compiling to managed code, the compiler translates your source code into Microsoft intermediate language (MSIL), which is a CPU-independent set of instructions that can be efficiently converted to native code.

Need appriication becuase MSIL is CPU-indipendent set of instruction that can be converted to native code. with MSIL system produce metadata which describes the types in your code incuding definition of each type and other data that the runtime uses. Beucause of metadata in the file makes it self describe which means there is no need for type libraries or interface definition language.

Note:
MSIL includes instructions for loading, storing, initializing, and calling methods on objects, as well as instructions for arithmetic and logical operations, control flow, direct memory access, exception handling, and other operations. Before code can be run, MSIL must be converted to CPU-specific code, usually by a just-in-time (JIT) compiler. Because the common language runtime supplies one or more JIT compilers for each computer architecture it supports, the same set of MSIL can be JIT-compiled and run on any supported architecture.

When a compiler produces MSIL, it also produces metadata. Metadata describes the types in your code, including the definition of each type, the signatures of each type's members, the members that your code references, and other data that the runtime uses at execution time.

The presence of metadata in the file along with the MSIL enables your code to describe itself, which means that there is no need for type libraries or Interface Definition Language (IDL). The runtime locates and extracts the metadata from the file as needed during execution.
--------------------------------
22. In what order do the events of an ASPX page execute. As a developer is it important to undertsand these events?

--------------------------------
23. Which method do you invoke on the DataAdapter control to load your generated dataset with data?
dataadapter.fill(dataset)
--------------------------------
24. Can you edit data in the Repeater control?
--------------------------------------------------------------------
NO ( Guess so.)
Note :
The Repeater control must be bound to a data source via its DataSource property or it will not render. The control can use as a data source any class that supports the IEnumerable interface. In practical terms, this means that you can use any type of data source that you can create using the Visual Studio data designers. You can also use data sources that you add to your page from the Toolbox, such as the DataSet or DataView class. You can also bind to simpler structures, such as an array.

Controls in the templates may be bound to the data source of the Repeater control or to a separate data source. Binding the controls to the Repeater control guarantees that all the controls will display data items from the same data row. The syntax for binding the controls to the Repeater control uses "Container" as the data source, since the Repeater is the container for all the controls. The binding command has the following form:

<%# DataBinder.Eval(Container, "DataItem.PhoneNumber") %>

Events : Repeater.ItemCreated,Repeater.ItemCommand

The Repeater.ItemCommand Event is raised in response to button clicks in individual items. The event is designed to allow you to embed a Button, LinkButton, or ImageButton Web server control in an item template and then be notified if a user clicks the button. When a click occurs, the event is bubbled up to the Repeater control. The most common uses for the ItemCommand event are to program add, update, and delete behaviors to the Repeater control. Since all the button clicks raise the same ItemCommand event, there must be way to distinguish which button has been clicked. You can determine which button was clicked by setting each button's CommandName property to a unique string value. The ItemCommand property of the RepeaterCommandEventArgs parameter contains the CommandName of the button clicked.

--------------------------------
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?
Using AlternatingItemTemplate 's style property.
--------------------------------
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?
DataSource property & DataBind()
--------------------------------
28. What base class do all Web Forms inherit from?
System.Web.UI.Page
--------------------------------
29. What method do you use to explicitly kill a user's session?
Seession.abandon()

--------------------------------
30 How do you turn off cookies for one page in your site?
<%@ EnableSessionState=False %>
--------------------------------
31. Which two properties are on every validation control?
Type and enableClientScript

Type is use to check validation's data type and Enableclientscript property use to enable client side scripting

--------------------------------
32. What tags do you need to add within the asp:datagrid tags to bind columns ?
ASP:boundColumn inside column tag.




--------------------------------
33. How do you create a permanent cookie?

--------------------------------
34. What tag do you use to add a hyperlink column to the DataGrid?
in side the column tag.
--------------------------------
35. What is the standard you use to wrap up a call to a Web service

--------------------------------
36. Which method do you use to redirect the user to another page
without performing a round trip to the client?
server.transfer
--------------------------------
37. What is the transport protocol you use to call a Web service
HTTP

Note:
The last optional part of the SOAP specification defines what an HTTP message that contains a SOAP message looks like. This HTTP binding is important because HTTP is supported by almost all current OS's (and many not-so-current OS's). The HTTP binding is optional, but almost all SOAP implementations support it because it's the only standardized protocol for SOAP. For this reason, there's a common misconception that SOAP requires HTTP. Some implementations support MSMQ, MQ Series, SMTP, or TCP/IP transports, but almost all current XML Web services use HTTP because it is ubiquitous. Since HTTP is a core protocol of the Web, most organizations have a network infrastructure that supports HTTP and people who understand how to manage it already. The security, monitoring, and load-balancing infrastructure for HTTP are readily available today.



--------------------------------
38. True or False: A Web service can only be written in .NET
False.
--------------------------------
39.. What does WSDL stand for?

XML Web services provide a way to describe their interfaces in enough detail to allow a user to build a client application to talk to them. This description is usually provided in an XML document called a Web Services Description Language (WSDL) document.

--------------------------------
40. What property do you have to set to tell the grid which page to go
to when using the Pager object?
AllowPaging="True"
--------------------------------
41. Where on the Internet would you look for Web services?
UDDI
--------------------------------
42. What tags do you need to add within the asp:datagrid tags to bind
columns manually.

--------------------------------
43. 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 To show the text in combo box
DataValueField to keep the value of text.
--------------------------------
44. How is a property designated as read-only?

--------------------------------
45. Which control would you use if you needed to make sure the values
in two different controls matched?
asp:CompareValidator
using below two property
ControlToCompare= txtpassword
test ControlToValidate = txtconfirmpass
--------------------------------
46. True or False: To test a Web service you must create a windows
application or Web application to consume this service?
False
--------------------------------
47. How many classes can a single .NET DLL contain?
NO Limit
--------------------------------
48. Describe the role of inetinfo.exe, aspnet_isapi.dll and aspnet_wp.exe in the page loading process.

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

inetinfo.exe
The inetinfo.exe process contains the many Internet services (HTTP, FTP, SMTP, NNTP) provided by IIS.
Inetinfo.exe receives requests from the TCP/IP subsystem and directs the requests to the respective services,
which in turn interpret the requests, execute them, and return the results to the client.
Because all of these services run within the same process (inetinfo.exe), they are able to share cached data such as file handles,
account information, and log file data.

aspnet_isapi.dll
What it really does is forward the request to another process called ASPNET_WP.EXE via a named pipe.
So it turns out that configuring your IIS virtual directory so that it runs out-of-process doesn't have any effect on where your managed code actually runs.
Interestingly enough, that configuration option doesn't even affect the security context of ASPNET_ISAPI.DLL because at installation time it is added to an IIS metabase property known as InProcessIsapiApps, which causes it to always run in-process.

So if you're building an ASP .NET application, don't waste your time configuring the application protection setting in IIS. It has absolutely no effect on where your managed code runs.


--------------------------------
49.What’s the difference between Response.Write() and Response.Output.Write()?
The latter one allows you to write formattedoutput.

--------------------------------
50.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.

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

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

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

56.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.

57.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();")


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

59.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.

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

61.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.

62.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.

63.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.

64.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.


65.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.

66. 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.

67.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.

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

69.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.

70.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.

71.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.

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

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

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

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

76.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.

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

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

79.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

80.What tag do you use to add a hyperlink column to the DataGrid?

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

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

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

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

85.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

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

87.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.

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

90.What is WSML?
Web Services Meta Language
WSML is best described as the Soap Toolkit configuration file. It contains the information required to map the Soap message described by a WSDL file to a COM interface. This includes the standard COM'isms like ProgID's and DispID's. WSML will never be a standard because it makes sense only to the Soap Toolkit.



--------------------------------------------------------------------------------------

OOP
For a programming language to be a true OOP language, the language must meet the following criteria:

Abstraction—Abstraction manages the complexities of a business problem by allowing you to identify a set of objects involved with that business problem.
Encapsulation—Encapsulation hides the internal implementation of an abstraction within the particular object.
Polymorphism—Polymorphism provides for multiple implementations of the same method. For example, different objects can have a Save method, each of which perform different processing.
Inheritance—The excitement of Visual Basic .NET lies in inheritance. Visual Basic 5 introduced the concept of interface inheritance, which allows you to reuse the interface of a class, but not its implementation. Visual Basic .NET provides for true implementation inheritance whereby you can reuse the implementation of a class.
Now let's look at doing object-oriented programming in .NET.
--------------------------------------------------------------------------------------------

Every object in .NET is inherited from a base class called System.Object.
This class is part of the Microsoft .NET Framework and contains the basic properties and methods required for a .NET object.

--------------------------------------------------------------------------------------------
If you do not put the Overrides keyword on the function in the derived class, the function is assumed to shadow the original function.
A shadowed function is a function in the derived class that has the same name as a function in the base class but is not intended to override the base class function.

---
-----------------------------------------------------------------------------
Finalize
--------------------------------------------------------------------------------
When an object is no longer needed, the CLR calls the Finalize method for that object before freeing its memory. The Finalize method is called a destructor because it performs cleanup tasks, such as saving state information, closing files and connections to databases, and other tasks that must be done before releasing the object.
The Finalize destructor is a protected method that can be called only from the class it belongs to, or from derived classes. The system calls Finalize automatically when an object is destroyed, so you should not explicitly call Finalize from outside of a derived class's Finalize implementation.

There is usually a delay between when an object loses scope and when Visual Basic .NET calls the Finalize destructor. Visual Basic .NET allows for a second kind of destructor, named Dispose, which can be explicitly called at any time to release resources immediately.

Unlike the Finalize destructor, the Dispose method is not called automatically. Clients of a class must explicitly call Dispose when you want to release resources.

Garbage Collection and the Finalize Destructor
------------------------------------------------------------------------------
The .NET Framework uses a system called reference-tracing garbage collection that periodically releases unused resources.

Nothing
-----------------------------------------------------
The Nothing keyword represents the default value of any data type.
Assigning Nothing to a variable sets it to the default value for its declared type.
If the variable is of a reference type — that is, an object variable — Nothing means the variable is not associated with any object.

When you assign Nothing to an object variable, it no longer refers to any object instance. If the variable had previously referred to an instance, setting it to Nothing does not terminate the instance itself.
The instance is terminated, and the memory and system resources associated with it are released, only after the garbage collector detects there are no active references remaining.

The CLR periodically destroys objects when the system determines that such objects are no longer needed. Objects are released more quickly when system resources are in short supply, and less frequently otherwise.
The .NET Framework uses a system called reference-tracing garbage collection that periodically releases unused resources.

Reflection Overview
-------------------------------------------------------------
You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object. You can then invoke the type's methods or access its fields and properties.


The common language runtime loader manages application domains. This management includes loading each assembly into the appropriate application domain and controlling the memory layout of the type hierarchy within each assembly.

Assemblies contain modules, modules contain types, and types contain members. Reflection provides objects that encapsulate assemblies, modules, and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object. You can then invoke the type's methods or access its fields and properties. Typical uses of reflection include the following:




Module
-----------------------------------------------------------------------
Modules are a reference type similar to classes, but with some important distinctions. The members of a module are implicitly Shared and scoped to the declaration space of the standard module's containing namespace, rather than just to the module itself. Unlike classes, modules can never be instantiated, do not support inheritance, and cannot implement interfaces. A module can only be declared in a namespace and cannot be nested in another type.

You can have multiple modules in a project, but members with the same name defined in two or more modules must be qualified with their module name when accessed outside of their module.


Namespaces
------------------------------------------------------------------------
Namespaces are used as an organizational system - a way of presenting program components that are exposed to other programs and applications.

Namespaces are always Public; therefore the declaration of a namespace cannot include access modifiers. However, the components within the namespace may have Public or Friend access. If it is not stated, the default access type is Friend.

Array and ArrayList
------------------------------------------------------------------------------
The capacity of an Array is fixed, whereas the capacity of an ArrayList is automatically expanded as required.
If the value of the ArrayList.Capacity property is changed, the memory reallocation and copying of elements are automatically done.
ArrayList provides methods that add, insert, or remove a range of elements.
In Array, you can get or set the value of only one element at a time.

A synchronized version of ArrayList is easy to create using the Synchronized method.
Array leaves it up to the user to implement synchronization.
ArrayList provides methods that return read-only and fixed-size wrappers to the collection. Array does not

You can set the lower bound of an Array, but the lower bound of an ArrayList is always zero.

An Array can have multiple dimensions, while an ArrayList always has exactly one dimension.

boxing and unboxing
--------------------------------------------------------------
An Array of a specific type (other than Object) has better performance than an ArrayList because the elements of ArrayList are of type Object and, therefore, boxing and unboxing typically occur if storing or retrieving a value type.

Visual Basic .NET Enhancements.
-------------------------------------------------------------------------
1. Major Language Enhancements
--> Object Oriented Support.
-->Structured Exception Handling.
2. Full Access to the .NET Framework.
-->New Threading Options
-->Garbaje Collection.
3.Enhanced Web Development
-->Create web forms as easy as windows forms
-->Create web services quickly

c# KeyWord Tokens....













Introduction



I expected that
learning C# would be easy considering my extensive C++ background.
Interestingly, I haven’t found this to be particularly true. There are subtle
differences between the languages which will trip up the C++ programmer, and
there’s quite a few new things in C# (and features that C++ has but are missing
from C#) to make life just a little more complicated than I expected. I
realized that while I am “functional” in C#, I am far from being “proficient”.



I figured it
was time to get back to basics and really explore the language in the way
languages used to be taught in the old days: start with the keywords, then move
into the syntax, and then start writing some basic (as in simple!) programs.



So, for all
those interested, this article gives a synopsis of the various keywords in C#.
The reader should be familiar with C++ or at least the concepts of classes and
objects. In some ways, this is a beginner’s tutorial, but in other ways, it can
be a very useful quick reference guide to the C++ veteran (especially the use
of the override and new modifiers).



A really good
place to begin is this site
<http://msdn.microsoft.com/library/default.asp?url=/library/en-us/csref/html/vcoricprogrammersreference.asp>

provided by Microsoft.



The Keywords



Following is a
table of the keywords in C#. Unfortunately, they are organized alphabetically,
instead of categorically.





























































































































abstract



event



new



struct



as



explicit



null



switch



base



extern



object



this



bool



false



operator



throw



break



finally



out



true



byte



fixed



override



try



case



float



params



typeof



catch



for



private



uint



char



foreach



protected



ulong



checked



goto



public



unchecked



class



if



readonly



unsafe



const



implicit



ref



ushort



continue



in



return



using



decimal



int



sbyte



virtual



default



interface



sealed



volatile



delegate



internal



short



void



do



is



sizeof



while



double



lock



stackalloc





else



long



static





enum



namespace



string






Note that
“value” is left out of this list, but it is syntax highlighted like a keyword
in the IDE.



Let’s take this
list and create some categories so that we can better organize and understand
the keywords. Now, a disclaimer: I am not a compiler expert, nor have I cracked
open a book on programming in a long time, so you’ll have to forgive me if you
don’t like the categorization of some of your favorite keywords!



Keywords that modify a class, method,
property, or field:



·
abstract



·
const



·
extern



·
internal



·
new



·
override



·
private



·
protected



·
public



·
readonly



·
sealed



·
static



·
virtual



·
volatile



·
void



Keywords dealing with object type and
type conversions:



·
as



·
explicit



·
implicit



·
is



·
operator



·
sizeof



·
typeof



Keywords that are aliases to built in
types, are specific types, or have to do with enumerations:



·
bool



·
byte



·
char



·
class



·
decimal



·
double



·
enum



·
float



·
int



·
interface



·
long



·
object



·
sbyte



·
short



·
string



·
struct



·
uint



·
ulong



·
ushort



Keywords that control program flow:



·
break



·
case



·
continue



·
default



·
do



·
else



·
for



·
foreach, in



·
goto



·
if



·
return



·
switch



·
while



Keywords that are used in exception
handling:



·
catch



·
checked



·
finally



·
throw



·
try



·
unchecked



Keywords that are like C++ function
pointers and related subjects:



·
delegate



·
event



Keywords that affect garbage
collection:



·
fixed



Keywords to help with critical sections
of code:



·
lock



Keywords that declare scope:



·
namespace



Keywords that control object
allocation/destruction:



·
new



·
stackalloc



Keywords that affect method parameter
passing:



·
out



·
params



·
ref



Keywords that are literals or refer to
the current instance of an object:



·
null



·
false



·
true



·
this



·
value



Keywords dealing with unmanaged code:



·
unsafe



Keywords, miscellaneous:



·
base



·
void



Keywords That Modify Accessibility



In Part I, I'll
look specifically at the keywords that modify the accessibility of classes,
methods, fields and properties. MSDN provides excellent descriptions of these
keywords, so I have two choices here—I can either plagiarize what they’ve
already done, or I could write my own descriptions based on my own
understanding, which may or may not be as complete, accurate or useful. I opted
for the second option, as this way, I’ll end up writing little code snippets to
try things out, and I’ll have learned something along the way (whether you will
learn something, well, I don’t know about that).



abstract



Abstract
class



When used as a
modifier for a class, this keyword declares the class as being intended to be
used only as a base class for other classes. You cannot directly instantiate an
abstract class. For this reason, the sealed modifier can’t be used, because
this prevents an abstract class from being inherited. An abstract class can
have members that implement actual functionality, as compared to an interface.



Abstract
classes are useful when providing generic functionality to a class structure.
As the name implies, an abstract class should represent the abstraction of some
object.



Abstract
method



When used as a
modifier for a method, the method does not have an implementation—the
implementation must be provided by the derived class. Because abstract methods
are implicitly virtual (meaning a derived class must provide the
implementation), the derived class must use the keyword override as part of the
declaration of the inherited class’ abstract method.



Abstract
methods are useful as a placeholder for a common process shared by specific
implementations. Unlike virtual methods, in which the base class can provide
some generic implementation, an abstract method forces the programmer to
provide an implementation in all derived classes. This may be done because
there is no generic implementation that is reasonable to provide.



Abstract
attribute



An attribute
can be abstract as well, which also requires that its implementation be
provided by the derived class. Furthermore, abstract attributes cannot be
static because they must be implemented in the derived class.



Abstract
attributes are useful in the same situations as described for abstract methods.



Example:























Collapse



abstract class AbstractClass



{



public int
i=5;



public
void Method()



{




Console.WriteLine("AbstractClass::Method() i="+i.ToString());



}





// can't
have an implementation:



public
abstract void AbstractMethod();





// the
property cannot have an implementation either:



public
abstract int I



{



get;



}



}





class ConcreteClass : AbstractClass



{



// because
there's an abstract method in the inherited class,



// we have
to provide the implementation here. Note
that we must



// also
provide the "override" keyword.



public
override void AbstractMethod()



{




Console.WriteLine("ConcreteClass:AbstractMethod");



}





//
similarly, for the property:



public
override int I



{



get
{return i;}



}



}





// can't do: AbstractClass abstractClass=new
AbstractClass();



ConcreteClass concreteClass=new ConcreteClass();



concreteClass.Method();



concreteClass.AbstractMethod();



Console.WriteLine("I="+concreteClass.I.ToString());



const and readonly



The const
keyword only applies to variables, which MSDN calls “fields”. A field with the
const keyword indicates that the field cannot be changed. The value of the
field must be initialized in the declaration. Interestingly, attributes cannot
be declared as const, and furthermore, attributes referring to const fields can
only have getters, not setters.



In C++, the const keyword was
also used to indicate that the method did not modify any variables:



void Foo() const;



or that the
method returned a reference that could not be modified:



const int& Foo();



or that the
parameter being passed as a reference could not be modified by the method:



void Foo(const int& i);



which could
lead to some ridiculous but valid statements:



const int& Foo(const int& i) const;



Happily, C#
treats the keyword const with only one meaning.



Declaring
fields as const protects both you and other programmers from accidentally
changing the value of the field. Also note that with const fields, the compiler
performs some optimization by not declaring any stack space for the field. For
example:



const int foo=10;



int bar=16;



results in
stack space being used for bar:



00000020 mov
dword ptr [ebp-8],10h



but not for foo, which is loaded
into a register as an immediate value:



Console.WriteLine("foo="+foo.ToString()+",
bar="+bar.ToString());



00000096
mov dword ptr
[ebp-18h],0Ah ; foo



0000009d
mov edi,dword ptr
ds:[01C40070h]



000000a3
lea ecx,[ebp-18h]



000000a6
call dword ptr
ds:[02EA2758h]



000000ac
mov dword ptr
[ebp-1Ch],eax



000000af
mov eax,dword ptr
ds:[01C40074h]



000000b5
mov dword ptr
[ebp-20h],eax



000000b8
lea ecx,[ebp-8] ; bar



Furthermore,
const can only be applied to intrinsic types. You can’t say:



const HasConstField hcf2=new HasConstField();



Example:



class HasConstField



{



public
HasConstField(); // can't do: {i=3;}



public
const int i=1;





public int
I



{



get
{return i;}



//
can't do: set {i=5;}



}



}



HasConstField hcf=new HasConstField();



// can't do: hcf.i=3;



The readonly
keyword is similar to const, with two exceptions. First, the storage of a
readonly field is the same as a regular (read-write) field, and thus there is
no performance benefit. Secondly, readonly fields can be initialized in the
constructor of the containing class.



For example
(from MSDN):



public class ReadOnlyTest



{



class
MyClass



{



public
int x;



public
readonly int y = 25; // Initialize a readonly field



public
readonly int z;





public
MyClass()



{



z =
24; // Initialize a readonly instance
field



}





public
MyClass(int p1, int p2, int p3)



{



x =
p1;



y =
p2;



z =
p3;



}



}



}



extern



The extern
keyword is basically used just for non-C# function calls, which also requires:



using System.Runtime.InteropServices;



and is used in
conjunction with the DllImport attribute, so that your C# program can call
functions in other DLLs. This is a very useful capability of the C# language,
because there are cases where you need direct access to the underlying Windows
API.



Example:



[DllImport("User32.dll")]



public static extern int MessageBox(int h, string m,
string c, int type);





MessageBox(0, "Test", "My Message
Box", 0);



internal



The internal
keyword restricts the visibility of the member to just the specific files in
the assembly in which the internal class is declared.



For classes, an
internal class and its members (public or not) are not visible to any programs
that reference the assembly.



For methods,
fields and properties, using the internal keyword limits the visibility of that
member to just the assembly. Thus, you can have a class visible to the outside
world, but the class can contain methods, fields and properties that are
visible only within the assembly. Compare this to the protected and private
keywords, which restrict access of members to derived classes and the class
methods themselves, respectively.



Also, all
internal members are treated as public within the scope of the assembly. The
only exception to this is the “protected internal” member which limits access
to just derived classes. This allows the programmer to control the access to
the member within the assembly (ensuring non-derived objects don’t tamper with
the value or access the function), while also making the method or field
inaccessible outside of the assembly.



Example:





Collapse



// This class is only visible to this assembly.



internal class InternalClass



{



}





class InternalTestClass



{



// this
field is visible only within this assembly.



internal
int i=2;



// this
method is visible only within this assembly.



internal
void InternalMethod()



{




Console.WriteLine("InternalMethod");



}



// this
protected method can only be invoked by derived classes.



internal
protected void InternalProtectedMethod()



{




Console.WriteLine("InternalProtectedMethod");



}



// this
attribute is visible only within this assembly.



internal
int I



{



get
{return i;}



set
{i=value;}



}



}





InternalTestClass itc=new InternalTestClass();



itc.I+=5;



Console.WriteLine("I="+itc.i.ToString());



itc.InternalMethod();



new, override, and virtual



Well, just when
I thought C# tried to give only one meaning to keywords, I discover this gem.
The keyword new, in addition to being used as an operator, can be used as a
modifier to explicitly hide a member inherited from a base class (MSDN).
Furthermore, MSDN states: Using new and virtual together guarantees a new point
of specialization. Compare this with the MSDN definition for virtual: An
override method provides a new implementation of a member inherited from a base
class. Let’s explore what all this means. Also note that it is impossible to
discuss the new modifier without also discussing the override modifier,
therefore these two have been lumped together.



To
explicitly hide a member inherited from a base class



First off, the
new modifier is used exclusively with members of a derived class. A basic use
of the new modifier is to declare a method in the derived class that just so
happens to have the same name as a method in the base class. Without the new
modifier, one gets the well known error “foo hides inherited member blah”,
which is a common problem in C++. The new modifier allows a method in the
derived class to have the same name as a method in the inherited class
(assuming all else is the same—return type and parameter lists).



Example 1:



class NewBaseClass



{



public
void NonVirtualMethod()



{




Console.WriteLine("NewBaseClass:NonVirtualMethod");



}



}





class NewClassA : NewBaseClass



{



public new
void NonVirtualMethod()



{




Console.WriteLine("NewClassA:NonVirtualMethod");




base.NonVirtualMethod();



}



}



In this
example, the NonVirtualMethod
method of the base class is hidden from the derived class, so it can have its
own implementation but use the same name.



Using new
and virtual together guarantees a new point of specialization



Now, things get
more interesting when the inherited method has been declared as virtual. First,
take a look at the following C# classes:



Example 2A:



class VirtualClass



{



public
virtual void VirtualMethod()



{




Console.WriteLine("VirtualClass:VirtualMethod");



}



}





class OverrideClassA : VirtualClass



{



public
override void VirtualMethod()



{




Console.WriteLine("OverrideClassA:VirtualMethod");




base.VirtualMethod();



}



}





class OverrideClassB : OverrideClassA



{



public
override void VirtualMethod()



{




Console.WriteLine("OverrideClassB:VirtualMethod");




base.VirtualMethod();



}



}



and the test
code:



Example 2B:



OverrideClassB ocb=new OverrideClassB();



ocb.VirtualMethod();



((OverrideClassA)ocb).VirtualMethod();



((VirtualClass)ocb).VirtualMethod();



resulting in:



OverrideClassB:VirtualMethod



OverrideClassA:VirtualMethod



VirtualClass:VirtualMethod



OverrideClassB:VirtualMethod



OverrideClassA:VirtualMethod



VirtualClass:VirtualMethod



OverrideClassB:VirtualMethod



OverrideClassA:VirtualMethod



VirtualClass:VirtualMethod



Now compare the
above class definition with the following:



Example 2C:



class NewBaseClass



{



public
virtual void VirtualMethod()



{




Console.WriteLine("NewBaseClass:VirtualMethod");



}



}





class NewClassA : NewBaseClass



{



public new
void VirtualMethod()



{




Console.WriteLine("NewClassA:VirtualMethod");




base.VirtualMethod();



}



}





class NewClassB : NewClassA



{



public new
void VirtualMethod()



{




Console.WriteLine("NewClassB:VirtualMethod");




base.VirtualMethod();



}



}



And note the
use of the new modifier. When the following code is run:



Example 2D:



NewClassB ncb=new NewClassB();



ncb.VirtualMethod();



((NewClassA)ncb).VirtualMethod();



((NewBaseClass)ncb).VirtualMethod();



we get:



OverrideClassB:VirtualMethod



OverrideClassA:VirtualMethod



VirtualClass:VirtualMethod



OverrideClassA:VirtualMethod



VirtualClass:VirtualMethod



VirtualClass:VirtualMethod



Now, the cast
allows us to access the specific base class member, because the derived class
provides a new specialization, meaning that it doesn’t simply provide an
implementation of the base class method, it provides a specialization. This is a
critical distinction.



When
implementing a class, the programmer must consider whether the class methods
provide specialization vs. always override the base class functionality. One
rule of thumb is to always assume specialization, except in the case of abstract
classes, methods or interfaces, all of which must be overridden by the derived
class.



Note that if
the inherited class’ method has been declared private, it is already hidden
from the derived class and therefore the new modifier is not necessary. Also
note that a virtual member cannot be private, because it is impossible to
override a private member—it is private to the class that implements it.



One final
point—inspecting the resulting assembly code shows that there is no difference
in performance between invoking members that are modified with the new keyword
vs. the override keyword.



private, protected, and public



These three
modifiers affect the accessibility of methods, fields and attributes. The
private modifier ensures that the method, field or attribute is visible only
within the class it is defined. The protected modifier extends this visibility
to derived classes, and the public modifier declares the method, field or
attribute to be visible to everyone.



These three
modifiers are fundamental to a good object oriented design. Much progress can
be made towards reducing potential bugs by restricting visibility and access to
methods, fields and attributes. However, inappropriate use of these modifiers
can result in classes that are not extensible because visibility/access is
incorrectly configured.



For example:



class PPP



{



private
int a=0;



public int
A



{



get
{return a;}



set
{a=value;}



}



protected
int A2



{



get
{return a*2;}



set
{a=value/2;}



}



public int
GetA() {return a;}



protected
int GetA2() {return a*2;}



private
void SetA2(int a2) {a=a2/2;}



}



sealed



The sealed
modifier ensures that a class cannot be inherited. Therefore, sealed classes
cannot be abstract, nor can they have abstract or virtual methods. There have
been several complaints that some classes in the .NET environment shouldn’t
have been sealed by the designers at Microsoft, so be careful when considering
whether to seal your own classes. Similar to using the public, protected and
private modifiers, using the sealed modifier on a class can make your object
model difficult, if not impossible, to extend.



static



A method, field
or property that has been modified with the static keyword is accessible
without requiring an instance of the containing class. A static field is shared
between all instances of an object. Also, methods and fields modified by the
static keyword is a mechanism for providing “global” functions and variables.



For example:



class StaticClass



{



public
static int a=0;





public int
A



{



get
{return a;}



set
{a=value;}



}



}





StaticClass sc1=new StaticClass();



StaticClass sc2=new StaticClass();



sc1.A=10;



Console.WriteLine("sc2.A="+sc2.A.ToString());



StaticClass.a=20;



Console.WriteLine("sc1.A="+sc1.A.ToString());



Console.WriteLine("sc2.A="+sc2.A.ToString());



Outputs:



Sc2.A=10



Sc1.A=20



Sc2.A=20



Illustrating
how even though a
was set using instance sc1,
it affected instance s1,
and similarly how field a
can be set without even needing an instance of the class, and its effects on
instances.



volatile



This keyword
modifies how the compiler generates code that reads and writes the contents of
a field that uses this keyword. Using the volatile modifier ensures that the
compiler generates code that always reads from the field’s memory location (as
opposed to optimizing by perhaps re-using a register that was previously loaded
with the field’s value), and immediately writes a value to the field (as
opposed to postponing the write because it may be more efficient to do it
later).



This keyword is
useful when an external process (like the operating system or a thread in your
application) can potentially modify the value of a field, and you need to
ensure that you are reading the most current value.



Unfortunately,
I cannot seem to get the C# compiler to generate code to demonstrate the
differences between volatile and non-volatile memory reads, even with the
optimization flag turned on. This is probably because of poor optimization in
C#.



void



The void
keyword modifies a method, indicating that it does not have a return value.
Unlike C++, you cannot use the void keyword in the argument list, which was an
allowable (if not acceptable) practice for indicating that a method did not
have any parameters.



Conclusion



By thoroughly
reviewing the keywords in C#, especially the modifier keywords, the transition
from C++ to C# can be much less confusing and much simpler for the programmer.