Posts

Showing posts from November, 2007

C#'s Approach to Inheritance: Interfaces and Multiple Inheritance

Q1: What is multiple inheritance, and why doesn’t C# support it? Multiple inheritance is a feature in some programming languages that allows a class to inherit properties and behaviors from more than one parent class. It introduces complexity and the potential for the “diamond problem,” where ambiguities arise when a class inherits from two classes with a common ancestor. Why C# avoids it: C# deliberately avoids multiple inheritance with classes to prevent complications and ambiguity. The language encourages a safer and more flexible approach using interfaces. Q2: What is the role of interfaces in C#? Interfaces in C# are contracts that define a set of methods, properties, and events. A class implementing an interface commits to providing concrete implementations for all declared members. C# allows a class to implement multiple interfaces. Q3: How do interfaces provide flexibility in C#? Flexibility with interfaces: Interfaces allow a class to implement multiple contracts, o

What is Static Constructor ?

It is a special type of constructor, introduced with C#. It gets called before the creation of the first object of a class(probably at the time of loading an assembly). See example below. public class SomeClass ( ) { static SomeClass ( ) { //Static members may be accessed from here //Code for Initialization } }

How do I calculate a MD5 hash from a string?

It is a common practice to store passwords in databases using a hash. MD5 (defined in RFC 1321 ) is a common hash algorithm, and using it from C# is easy. Here’s an implementation of a method that converts a string to an MD5 hash, which is a 32-character string of hexadecimal numbers. public string CalculateMD5Hash ( string input ) { // step 1, calculate MD5 hash from input MD5 md5 = System . Security . Cryptography . MD5 . Create ( ) ; byte [ ] inputBytes = System . Text . Encoding . ASCII . GetBytes ( input ) ; byte [ ] hash = md5 . ComputeHash ( inputBytes ) ; // step 2, convert byte array to hex string StringBuilder sb = new StringBuilder ( ) ; for ( int i = 0 ; i < hash . Length ; i ++ ) { sb . Append ( hash [ i ] . ToString ( "X2" ) ) ; } return sb . ToString ( ) ; } An example call: string hash = CalculateMD5Hash ( "abcdefghijklmnopqrstuvwxyz" ) ; …returns a s

What is the difference between const and static readonly?

When dealing with constants in C#, it’s essential to understand the difference between static readonly and const fields. Both are used to represent values that shouldn’t change during the program’s execution, but they have distinct characteristics. const Fields const fields are set to a compile-time constant and cannot be modified afterward. They are implicitly static and are implicitly readonly . The value must be known at compile time. const fields are implicitly static , meaning they belong to the type rather than an instance. They are set during compilation and can’t be changed at runtime. Commonly used for primitive types and strings. class Program { public const int MaxValue = 100 ; static void Main ( string [ ] args ) { // Error: A constant value cannot be modified // MaxValue = 200; } } static readonly Fields static readonly fields are set at runtime and can be modified only in the variable declaration or w

What’s the difference between System.String and System.StringBuilder classes?

While System.String is immutable, meaning its value cannot be changed once it’s created, System.StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed. StringBuilder is more efficient for scenarios where you need to make many modifications to a string, as it avoids the overhead of creating a new string instance for each change.

Does C# support multiple inheritance?

No, use interfaces instead.

Can you inherit multiple interfaces?

Yes, why not. Through Interface we can achieve

What is Overriding?

A process of creating different implementation of a method having a same name as base class, in a derived class. It implements Inheritance. When we need to provide different implementation than the provide by base class, We define the same method with same signatures in the derived class. Method must be Protected/Protected-Friend/Public for this purpose. (Base class routine can be called by Mybase.Method, base.Method).

What is Shadowing?

In C#, when a method in a base class is marked as sealed (also known as final in some languages), it means that the method cannot be overridden in derived classes. However, if you still need to provide a different implementation in a derived class, you can use method shadowing with the new keyword. Let’s explore this concept through an example: using System ; // Base class with a sealed method public class BaseClass { public sealed void DisplayMessage ( ) { Console . WriteLine ( "Message from BaseClass" ) ; } } // Derived class shadowing the sealed method public class DerivedClass : BaseClass { // Using the 'new' keyword to shadow the method public new void DisplayMessage ( ) { Console . WriteLine ( "Message from DerivedClass" ) ; } } class Program { static void Main ( ) { // Creating instances of both base and derived classes BaseClass baseObj

Difference between Overloading and Overriding ?

Overloading: Overloading refers to the ability to define multiple methods in the same class with the same name but different parameters. The compiler differentiates between these methods based on the number or types of parameters. Here’s an example: public class Example { public void PrintSum ( int a , int b ) { Console . WriteLine ( $ "Sum: {a + b}" ) ; } public void PrintSum ( int a , int b , int c ) { Console . WriteLine ( $ "Sum: {a + b + c}" ) ; } } In this example, we have two methods named PrintSum . One takes two integers, and the other takes three. The compiler determines which method to call based on the number of arguments provided. Overriding: Overriding is a concept related to inheritance and polymorphism. It occurs when a derived class provides a specific implementation for a method that is already defined in its base class. To override a method, both the base and derived methods m

How a base class method is hidden?

Hiding a base class method by declaring a method in derived class with keyword new . This will override the base class method and old method will be suppressed.

What is CLR (Common Language Runtime)?

CLR provides a environment in which program are executed, it activate object, perform security check on them, lay them out in the memory, execute them and garbage collect them. The common Language Runtime (CLR) a rich set of features for cross-language development and deployment. CLR supports both Object Oriented Languages as well as procedural languages. CLR provides security, garbage collection, cross language exception handling, cross language inheritance and so on.

What is CTS (Common Type System) ?

The common type system defines how types are declared, used, and managed in the runtime, and is also an important part of the runtime's support for cross-language integration. The common type system performs the following functions: Establishes a framework that helps enable cross-language integration, type safety, and high performance code execution. Provides an object-oriented model that supports the complete implementation of many programming languages. Defines rules that languages must follow, which helps ensure that objects written in different languages can interact with each other.

What are the different types of Assemblies?

Different types of assemblies are Priave, Public/Shared, Static, Dynamic assembly . Private Assemblies : Assembly used within an application is known as private assemblies Public/shared Assemblies : Assembly which can be shared across applicaiton is known as shared assemblies. Strong Name has to be created to create a shared assembly. This can be done using SN.EXE. The same has to be registered using GACUtil.exe (Global Assembly Cache). Satellite Assemblies : These assemblies contain resource files pertaining to a locale (Culture+Language). These assemblies are used in deploying an Gloabl applicaiton for different languages. Static assemblies can include .NET Framework types (interfaces and classes), as well as resources for the assembly (bitmaps, JPEG files, resource files, and so on). Static assemblies are stored on disk in portable executable (PE) files. Dynamic Assemblies : You can also use the .NET Framework to create dynamic assemblies, which are run directly from

What is a bubbled event?

When a complex control like datalist or datagrid, which contains a child control, using an itemcommand can listen to the events raised by the child control in the main control. The process of listening to the child control in the main or parent control is called as event bubbling.

What are the types of Authentication?

There are 3 types of Authentication. Windows, Forms and Passport Authentication . Windows authentication uses the security features integrated into the Windows NT and Windows XP operating systems to authenticate and authorize Web application users. Forms authentication allows you to create your own list/database of users and validate the identity of those users when they visit your Web site. Passport authentication uses the Microsoft centralized authentication provider to identify users. Passport provides a way to for users to use a single identity across multiple Web applications. To use Passport authentication in your Web application, you must install the Passport SDK.

What is Authentication and Authorization?

Authentication is the process of identifying users. Authentication is identifying/validating the user against the credentials (username and password) and Authorization performs after authentication. Authorization is the process of granting access to those users based on identity. Authorization allowing access of specific resource to user.

What is Remoting?

Remoting is a means by which one operating system process, or program, can communicate with another process. The two processes can exist on the same computer or on two computers connected by a LAN or the Internet. Web services are probably the best known type of remoting, but they are not the only option.

What is Marshalling?

Marshaling is a process of making an object in one process (the server) available to another process (the client). There are two ways to achieve the marshalling. i. Marshal by value: the server creates a copy of the object passes the copy to the client. When a client makes a call to an object marshaled by value (MBV), the server creates an exact copy and sends that copy to the client. The client can then use the object's data and executable functionality directly within its own process or application domain without making additional calls to the server. Objects that the application accesses frequently are best remoted using MBV. ii. Marshal by reference: the client creates a proxy for the object and then uses the proxy to access the object. When a client makes a call to an object marshaled by reference (MBR), the .NET framework creates a proxy in the client's application domain and the client uses that proxy to access the original object on the server. Large objects that th

What is serialization?

Serialization is the process of converting an object into a stream of bytes. De-serialization is the opposite process of creating an object from a stream of bytes. Serialization/De-serialization is mostly used to transport objects (e.g. during remoting), or to persist objects (e.g. to a file or database). There are two separate mechanisms provided by the .NET class library for serialization - XmlSerializer and SoapFormatter and BinaryFormatter. Microsoft uses XmlSerializer for Web Services, and uses SoapFormatter/BinaryFormatter for remoting.

What is a Page Life Cycle of an ASP.Net page?

There are various stages described as under. Init LoadViewState LoadPostBackData Load RaisePostBackDataChangedEvent RaisePostBackEvents Pre-Render SaveViewState Render Unload

Difference between managed and unmanaged code?

Managed Code : Code that is executed by the CLR is Managed code Unmanaged Code : Code that is directly executed by the Operating System, not by CLR is known as un-managed code .

What is reflection?

All .NET compilers produce metadata about the types defined in the modules they produce. This metadata is packaged along with the module (modules in turn are packaged together in assemblies), and can be accessed by a mechanism called reflection. The System.Reflection namespace contains classes that can be used to interrogate the types for a module/assembly. Reflection is ability to find information about types contained in an assembly at run time.

What is the lifespan fo What is the lifespan for items stored in ViewState?r items stored in ViewState?

Items stored in a ViewState exist for the life of the current page, including the post backs on the same page

Can we disable ViewState, If, yes how?

ViewState can be disabled by using "EnableViewState" property set to false.

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.

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.

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.

What is Postback?

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

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.

List the ASP.NET validation controls?

RequiredFieldValidator RangeValidator CompareValidator RegularExpressionValidator CustomValidator ValidationSummary

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.

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.

What is Static Assembly?

A static assembly is created when you compile the program using any of the .NET language compilers . A static assembly contains the types, interfaces, and various resources required by the assembly. A static assembly is stored on the hard disk in the form of a portable executable (.exe or .dll) file. In a simple term, when you compile through VS.Net it generates files which are physically stored on the disk, this files are called static assembly.

What is Dynamic Assembly?

Assemblies which are created and execute on the fly are called dynamic assembly. You can create dynamic assembly through System.Reflection.Emit namespace

What is Satellite Assembly?

Resource-only assemblies are assembly's that stores only resource and no code. example, Image. Resource-only assemblies that store the culture-specific information are known as satellite assemblies

What is Private Assembly?

When you deploy an assembly which can be use by single application, than this assembly is called a private assembly. Private assemblies can be used by only one application they are deployed with. Private assemblies are deployed in the directory where the main application is installed.

What is WSDL?

WSDL stands for Web Service Description Language, a standard by which a web service can tell clients what messages it accepts and which results it will return. WSDL contains every details regarding using web service Method and Properties provided by web service URLs from which those method can be accessed. Data Types used. Communication Protocol used.

What is UDDI?

UDDI allows you to find web services by connecting to a directory.

What is difference between Disco and UDDI?

Disco is Microsoft's Standard format for discovery documents which contains information about Web Services, while UDDI is a multi-vendor standard for discovery documents which contains information about Web Services.

What is Proxy Class?

A proxy class is code that looks exactly like the class it meant to represent; however the proxy class doesn't contain any of the application logic. Instead, the proxy class contains marshalling and transport logic. A proxy class object allows a client to access a web service as if it were a local COM object. The Proxy must be on the computer that has the web application .

What is Component?

It is a set pre-compiled class, which is reusable. For now, just stick to it at the end of article you will practically understand how it is reusable piece of code.

what is Difference between Struct and Class

Struct are Value type and are stored on stack, while Class are Reference type and are stored on heap. Struct “do not support” inheritance, while class supports inheritance. However struct can implements interface. Struct should be used when you want to use a small data structure, while Class is better choice for complex data structure.

What is the difference between instantiating structures with and without using the new keyword?

When a structure is instantiated using the new keyword, a constructor (no-argument or custom, if provided) is called which initializes the fields in the structure. When a structure is instantiated without using the new keyword, no constructor is called. Hence, one has to explicitly initialize all the fields of the structure before using it when instantiated without the new keyword.

what is Constructor in c#

A constructor is a special method whose task is to initialize the object of its class. It is special because its name is the same as the class name. They do not have return types, not even void and therefore they cannot return values. They cannot be inherited, though a derived class can call the base class constructor. Constructor is invoked whenever an object of its associated class is created. Note: There is always atleast one constructor in every class. If you do not write a constructor, C# automatically provides one for you, this is called default constructor. Eg: class A, default constructor is A().

What is the difference between the destructor and the Finalize() method? When does the Finalize() method get called?

Finalize() corresponds to the .Net Framework and is part of the System.Object class. Destructors are C#'s implementation of the Finalize() method. The functionality of both Finalize() and the destructor is the same, i.e., they contain code for freeing the resources when the object is about to be garbage collected. In C#, destructors are converted to the Finalize() method when the program is compiled. The Finalize() method is called by the .Net Runtime and we can not predict when it will be called. It is guaranteed to be called when there is no reference pointing to the object and the object is about to be garbage collected.

What is Garbage Collection in c#

Garbage collection is the mechanism that reclaims the memory resources of an object when it is no longer referenced by a variable. .Net Runtime performs automatically performs garbage collection, however you can force the garbage collection to run at a certain point in your code by calling System.GC.Collect(). Advantage of Garbage collection : It prevents programming error that could otherwise occur by incorrectly deleting or failing to delete objects.

What is Boxing and Un-Boxing?

Boxing : means converting value-type to reference-type. Eg: int I = 20; string s = I.ToSting(); UnBoxing : means converting reference-type to value-type. Eg: int I = 20; string s = I.ToString(); //Box the int int J = Convert.ToInt32(s); //UnBox it back to an int. Note: Performance Overheads due to boxing and unboxing as the boxing makes a copy of value type from stack and place it inside an object of type System.Object in the heap.

What is .Net Platform?

Microsoft .NET is a software development platform based on virtual machine architecture. Dot Net Platform is: Language Independent – dot net application can be developed different languages (such as C#, VB, C++, etc.) Platform Independent – dot net application can be run on any operating system which has .net framework installed. Hardware Independent – dot net application can run on any hardware configuration It allows us to build windows based application, web based application, web service, mobile application , etc.

What is .Net Framework?

.Net Framework provides a foundation upon which .net application and xml webservices are built and executed.

What is Two main Components of .Net Framework

Common Language Runtime Base Class Library.

What is MSIL?

An intermediate language generated by compiler is called MSIL. All .Net assemblies are represented in MSIL. The main Advantage of using MSIL is it provides equal performance for multiple language programming, as code is compiled to native code.

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.

What’s the difference between Response.Write() and Response.Output.Write()?

Response.Output.Write() allows you to write formatted output

What methods are fired during the page load?

Init() - when the page is instantiated Load() - when the page is loaded into server memory PreRender() - the brief moment before the page is displayed to the user as HTML Unload() - when page finishes loading.

When during the page processing cycle is ViewState available?

After the Init() and before the Page_Load(), or OnLoad() for a control.

What namespace does the Web page belong in the .NET Framework class hierarchy?

System.Web.UI.Page

Where do you store the information about the user’s locale?

System.Web.UI.Page.Culture

What’s the difference between Codebehind="MyCode.aspx.cs" andSrc="MyCode.aspx.cs"?

CodeBehind is relevant to Visual Studio.NET only.

Suppose you want a certain ASP.NET function executed on MouseOver for a certain button. Where do you add an event handler?

Add an OnMouseOver attribute to the button. Example: btnSubmit.Attributes.Add("onmouseover","someClientCodeHere();");

What data types do the RangeValidator control support?

Integer, String, and Date.

Explain the differences between Server-side and Client-side code?

Server-side code executes on the server. Client-side code executes in the client's browser.

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

The answer is server-side code since code-behind is executed on the server. However, during the code-behind's execution on the server, it can render client-side code such as JavaScript to be processed in the clients browser. But just to be clear, code-behind executes on the server, thus making it server-side code.

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

All user input data validation should occur on the server at a minimum. Additionally, client-side validation can be performed where deemed appropriate and feasable to provide a richer, more responsive experience for the user

What is the difference between Server.Transfer and Response.Redirect? Why would I choose one over the other?

Server.Transfer transfers page processing from one page directly to the next page without making a round-trip back to the client's browser. This provides a faster response with a little less overhead on the server. Server.Transfer does not update the clients url history list or current url. Response.Redirect is used to redirect the user's browser to another page or site. This performas a trip back to the client where the client's browser is redirected to the new page. The user's browser history list is updated to reflect the new address.

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.

What is the Global.asax used for?

The Global.asax (including the Global.asax.cs file) is used to implement application and session level events

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.

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

ItemTemplate.

How can you provide an alternating color scheme in a Repeater control?

Use the AlternatingItemTemplate.

What property must you set, and what method must you call in your code, in order to bind the data from a data source to the Repeater control?

You must set the DataSource property and call the DataBind method.

Name two properties common in every validation control?

ControlToValidate property and Text property.

What base class do all Web Forms inherit from?

The Page class.

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.

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

CompareValidator control.

How is .NET able to support multiple languages?

A language should comply with the Common Language Runtime standard to become a .NET language. In .NET, code is compiled to Microsoft Intermediate Language (MSIL for short). This is called as Managed Code. This Managed code is run in .NET environment. So after compilation to this IL the language is not a barrier. A code can call or use a function written in another language.

What is smart navigation?

The cursor position is maintained when the page gets refreshed due to the server side validation and the page gets refreshed.

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.

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.

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.

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.

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.

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

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.

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.

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.

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.

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.

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.

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.

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.

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 statement in the Web.config file.

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: 1. 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. 2. 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. 3. 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.

Can the view state be encrypted?

The view state can be encrypted by setting EnableViewStateMac to true and either modifying the element in Machine.config to or by adding the above statement to Web.config.

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.

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:

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.

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.

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.

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.

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 tag. Then, a byte[] can be declared to read in the data from the input file. This can then be sent to the server.

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

. Enumerate the types of Directives.

1. @ Page directive 2. @ Import directive 3. @ Implements directive 4. @ Register directive 5. @ Assembly directive 6. @ OutputCache directive 7. @ Reference directive

What is difference between ExecuteReader, ExecuteNonQuery and ExecuteScalar.

# ExecuteReader : Use for accessing data. It provides a forward-only, read-only, connected recordset. # ExecuteNonQuery : Use for data manipulation, such as Insert, Update, Delete. # ExecuteScalar : Use for retriving 1 row 1 col. value., i.e. Single value. eg: for retriving aggregate function. It is faster than other ways of retriving a single value from DB.

Strongly Typed Dataset Object

Strongly typed Dataset object allows you to create early-bound data retrieval expression. Advantage of Strongly Typed dataset * It is faster than late-bound data retrieval expression. * Its column name is shown in intellisense as you type code.

What is DataView?

It provides a means to filter and sort data within a data table. Example: DataView myDataView = new DataView(myDataSet.Tables["Customers"]); // Sort the view based on the FirstName column myDataView.Sort = "CustomerID"; // Filter the dataview to only show customers with the CustomerID of ALFKI myDataView.RowFilter = "CustomerID='ALFKI'";

Explain DataAdapter Object

It populates dataset from data source. It contains a reference to the connection object and opens and closes the connection automatically when reading from or writing to the database. Example: SqlDataAdapter daEmp = new SqlDataAdapter( "select EmpID, EmpName, Salary from Employees", conn); Fill Method It is used to populate dataset. example: daEmp.Fill(dsEmp,"Employee"); Update Method It is used to update database. example: daEmp.Update(dsEmp,"Employee");

What is DataReader Object?

It provides a forward-only, read-only, connected recordset. It is most efficient to use when data need not to be updated, and requires forward only traverse. In other words, it is the fastest method to read data. Example: 1. Filling dropdownlistbox. 2. Comparing username and password in database. SqlDataReader rdr = cmd.ExecuteReader(); //Reading data while (rdr.Read()) { //Display data string contact = (string)rdr["ContactName"]; string company = (string)rdr["CompanyName"]; string city = (string)rdr["City"]; }

What is ADO.NET?

ADO.net is data access architecture for the Microsoft .NET Framework. ADO.NET is an object-oriented set of libraries that allows you to interact with data sources. Commonly, the data source is a data base, but it could also be a text file, an Excel spread sheet, or an XML file.

What is C#?

C# is a programming language designed by Microsoft. It is loosely based on C/C++, and bears a striking similarity to Java. Microsoft describe C# as follows: "C# is a simple, modern, object oriented, and type-safe programming language derived from C and C++. C# (pronounced 'C sharp') is firmly planted in the C and C++ family tree of languages, and will immediately be familiar to C and C++ programmers. C# aims to combine the high productivity of Visual Basic and the raw power of C++."

What are the fundamental differences between value types and reference types?

C# divides types into two categories - value types and reference types. Most of the intrinsic types (e.g. int, char) are value types. Structs are also value types. Reference types include classes, arrays and strings. The basic idea is straightforward - an instance of a value type represents the actual data, whereas an instance of a reference type represents a pointer or reference to the data. The most confusing aspect of this for C++ developers is that C# has predetermined which types are represented as values, and which are represented as references. A C++ developer expects to take responsibility for this decision. For example, in C++ we can do this: int x1 = 3; // x1 is a value on the stack int *x2 = new int(3) // x2 is a pointer to a value on the heap but in C# there is no control: int x1 = 3; // x1 is a value on the stack int x2 = new int(); x2 = 3; // x2 is also a value on the stack!

int is a value type, and a class is a reference type. How can int be derived from object?

It isn't, really. When an int is being used as an int, it is a value. However, when it is being used as an object, it is a reference to an integer value (on the managed heap). In other words, when you treat an int as an object, the runtime automatically converts the int value to an object reference. This process is called boxing. The conversion involves copying the int to the heap, and creating an object instance which refers to it. Unboxing is the reverse process - the object is converted back to a value. int x = 3; // new int value 3 on the stack object objx = x; // new int on heap, set to value 3 - still have x=3 on stack int y = (int)objx; // new value 3 on stack, still got x=3 on stack and objx=3 on heap

How do I declare a pure virtual function in C#?

Use the abstract modifier on the method. The class must also be marked as abstract (naturally). Note that abstract methods cannot have an implementation (unlike pure virtual C++ methods).

Can I use exceptions in C#?

Yes, in fact exceptions are the recommended error-handling mechanism in C# (and in .NET in general). Most of the .NET framework classes use exceptions to signal errors.

How can I check the type of an object at runtime?

You can use the is keyword. For example: using System; class CApp { public static void Main() { string s = "fred"; long i = 10; Console.WriteLine( "{0} is {1}an integer", s, (IsInteger(s) ? "" : "not ") ); Console.WriteLine( "{0} is {1}an integer", i, (IsInteger(i) ? "" : "not ") ); } static bool IsInteger( object obj ) { if( obj is int || obj is long ) return true; else return false; } } produces the output: fred is not an integer 10 is an integer

Can I get the name of a type at runtime?

Yes, use the GetType method of the object class (which all types inherit from). For example: using System; class CTest { class CApp { public static void Main() { long i = 10; CTest ctest = new CTest(); DisplayTypeInfo( ctest ); DisplayTypeInfo( i ); } static void DisplayTypeInfo( object obj ) { Console.WriteLine( "Type name = {0}, full type name = {1}", obj.GetType(), obj.GetType().FullName ); } } } produces the following output: Type name = CTest, full type name = CTest Type name = Int64, full type name = System.Int64

What is the difference between typeof and GetType()?

Apart from the obvious (i.e. typeof operates on a type whereas GetType operates on an object), the main thing to watch out for is that GetType returns the underlying type of the object, which may not be the same as the type of the reference to the object. For example: class Base { } class Derived : Base { } class Program { static void Main() { ShowType( new Derived() ); } static void ShowType( Base b ) { Console.WriteLine(typeof(Base)); Console.WriteLine(b.GetType()); } } gives the following output: Base Derived

Does C# support a variable number of arguments?

Yes, using the params keyword. The arguments are specified as a list of arguments of a specific type, e.g. int. For ultimate flexibility, the type can be object. The standard example of a method which uses this approach is System.Console.WriteLine().

What is the difference between == and object.Equals?

For value types, == and Equals() usually compare two objects by value. For example: int x = 10; int y = 10; Console.WriteLine( x == y ); Console.WriteLine( x.Equals(y) ); will display: True True However things are more complex for reference types. Generally speaking, for reference types == is expected to perform an identity comparison, i.e. it will only return true if both references point to the same object. By contrast, Equals() is expected to perform a value comparison, i.e. it will return true if the references point to objects that are equivalent. For example: StringBuilder s1 = new StringBuilder("fred"); StringBuilder s2 = new StringBuilder("fred"); Console.WriteLine( s1 == s2 ); Console.WriteLine( s1.Equals(s2) ); will display: False True s1 and s2 are different objects (hence == returns false), but they are equivalent (hence Equals() returns true). Unfortunately there are exceptions to these rules. The implementation of Eq

Is it better to write code in C# or Visual Basic?

You can write code for your Web application in any language supported by the .NET Framework. That includes Visual Basic, C#, J#, JScript, and others. Although the languages have different syntax, they all compile to the same object code. The languages have small differences in how they support different features. For example, C# provides access to unmanaged code, while Visual Basic supports implicit event binding via the Handles clause. However, the differences are minor, and unless your requirements involve one of these small differences, the choice of programming language is one of personal preference. Once programs are compiled, they all perform identically; that is, Visual Basic programs run just as fast as C# programs, since they both produce the same object code.

Do I have to use one programming language for all my Web pages?

No. Each page can be written in a different programming language if you want, even in the same application. If you are creating source code files and putting them in the \App_Code folder to be compiled at run time, all the code in must be in the same language. However, you can create subfolders in the \App_Code folder and use the subfolders to store components written in different programming languages.

What's the difference between login controls and Forms authentication?

Login controls are an easy way to implement Forms authentication without having to write any code. For example, the Login control performs the same functions you would normally perform when using the FormsAuthentication class—prompt for user credentials, validate them, and issue the authentication ticket—but with all the functionality wrapped in a control that you can just drag from the Toolbox in Visual Studio. Under the covers, the login control uses the FormsAuthentication class (for example, to issue the authentication ticket) and ASP.NET membership (to validate the user credentials). Naturally, you can still use Forms authentication yourself, and applications you have that currently use it will continue to run.

What are the different types of caching?

Caching is a technique widely used in computing to increase performance by keeping frequently accessed or expensive data in memory. In context of web application, caching is used to retain the pages or data across HTTP requests and reuse them without the expense of recreating them.ASP.NET has 3 kinds of caching strategiesOutput CachingFragment CachingData CachingOutput Caching: Caches the dynamic output generated by a request. Some times it is useful to cache the output of a website even for a minute, which will result in a better performance. For caching the whole page the page should have OutputCache directive.<%@ OutputCache Duration="60" VaryByParam="state" %> Fragment Caching: Caches the portion of the page generated by the request. Some times it is not practical to cache the entire page, in such cases we can cache a portion of page<%@ OutputCache Duration="120" VaryByParam="CategoryID;SelectedID"%> Data Caching: Caches the objec

• How do I debug an ASP.NET application that wasn't written with Visual Studio.NET and that doesn't use code-behind?

Start the DbgClr debugger that comes with the .NET Framework SDK, open the file containing the code you want to debug, and set your breakpoints. Start the ASP.NET application. Go back to DbgClr, choose Debug Processes from the Tools menu, and select aspnet_wp.exe from the list of processes. (If aspnet_wp.exe doesn't appear in the list,check the "Show system processes" box.) Click the Attach button to attach to aspnet_wp.exe and begin debugging. Be sure to enable debugging in the ASPX file before debugging it with DbgClr. You can enable tell ASP.NET to build debug executables by placing a <%@ Page Debug="true" %> statement at the top of an ASPX file or a statement in a Web.config file.

• Is it necessary to lock application state before accessing it?

Only if you're performing a multistep update and want the update to be treated as an atomic operation. Here's an example: Application.Lock (); Application["ItemsSold"] = (int) Application["ItemsSold"] + 1; Application["ItemsLeft"] = (int) Application["ItemsLeft"] - 1; Application.UnLock ();

What is Static Constructor ?

It is a special type of constructor, introduced with C#. It gets called before the creation of the first object of a class(probably at the time of loading an assembly). See example below. Example: public class SomeClass() { static SomeClass() { //Static members may be accessed from here //Code for Initialization } }

What is Serialization?

Serialization - The process of converting an object into a stream of bytes. This stream of bytes can be persisted. Deserialization is an opposite process, which involves converting a stream of bytes into an object. Serialization is used usually during remoting (while transporting objects) and to persist file objecst & database objects. .NET provides 2 ways for serializtion 1) XmlSerializer and 2) BinaryFormatter/SoapFormatter The XmlSerializer is used for Web Services. The BinaryFormatter & SoapFormatter is used for Remoting. While using XmlSerializer, it is required that the target class has parameter less constructors, has public read-write properties and has fields that can be serialized. The XmlSerializer has good support for XML documents. It can be used to construct objects from existing XML documents. The XmlSerializer enables us to serialize and deserialize objects to an XML format. SoapFormatter enables us to serialize & deserialize objects to SOAP format. They can