Tuesday, December 9, 2008

Can we bind data to a server control without writing code in .NET?

Can we bind data to a server control without
writing code in .NET?


Yes, that is possible. ASP.NET 2.0 has the feature
of declarative solution for data binding which requires no
code at all for the most common data scenarios, such as:
*
Selecting and displaying
* Data Sorting
* Paging and
Caching
* Data Updating
* Inserting and Deleting Data



DESIGN PATTERN INTERVIEW QUESTIONS

What is a Design Pattern?

Design Pattern is a re-usable, high quality solution to a given requirement, task or recurring problem. Further, it does not comprise of a complete solution that may be instantly converted to a code component, rather it provides a framework for how to solve a problem.

In 1994, the release of the book Design Patterns, Elements of Reusable Object Oriented Software made design patterns popular.

Because design patterns consist of proven reusable architectural concepts, they are reliable and they speed up software development process.

Design Patterns are in a continious phase of evolution, which means that they keep on getting better & better as they are tested against time, reliability and subjected to continious improvements. Further, design patterns have evolved towards targeting specific domains. For example, windows-based banking applications are usually based on singleton patterns, e-commerce web applications are based on the MVC (Model-View-Controller) pattern.


Design Patterns are categorized into 3 types:
Creational Patterns
Structural Patterns
Behavioral Patterns


What are Creational Design Patterns?

The Creational Design Patterns focus on how objects are created and utilized in an application. They tackle the aspects of when and how objects are created, keeping in mind whats the best way these objects should be created.

Listed below are some of the commonly known Creational Design Patterns:
>>> Abstract Factory Pattern
>>> Factory Pattern
>>> Builder Pattern
>>> Lazy Pattern
>>> Prototype Pattern
>>> Singleton Pattern


Whats the difference between Abstract Factory Pattern and Factory Pattern?

In an abstract factory design, a framework is provided for creating sub-components that inherit from a common component. In .NET, this is achieved by creating classes that implement a common interface or a set of interfaces, where the interface comprises of the generic method declarations that are passed on to the sub-components. TNote that not just interfaces, but even abstract classes can provide the platform of creating an application based on the abstract factory pattern.
Example, say a class called CentralGovernmentRules is the abstract factory class, comprised of methods like ShouldHavePolice() and ShouldHaveCourts(). There may be several sub-classes like State1Rules, State2Rules etc. created that inheriting the class CentralGovernmentRules, and thus deriving its methods as well.

Note that the term "Factory" refers to the location in the code where the code is created.

A Factory Pattern is again an Object creation pattern. Here objects are created without knowing the class of the object. Sounds strange? Well, actually this means that the object is created by a method of the class, and not by the class's constructor. So basically the Factory Pattern is used wherever sub classes are given the priviledge of instantiating a method that can create an object.

Describe the Builder Design Pattern

In a builder design pattern, an object creation process is separated from the object design construct. This is useful becuase the same method that deals with construction of the object, can be used to construct different design constructs.

What is the Lazy Design Pattern?

The approach of the Lazy Design Pattern is not to create objects until a specific requirement matches, and when it matches, object creation is triggered. A simple example of this pattern is a Job Portal application. Say you register yourself in that site thus filling up the registration table, only when the registration table is filled, the other objects are created and invoked, that prompt you to fill in other details too, which will be saved in other tables.

What is the Prototype Design Pattern?

A prototype design pattern relies on creation of clones rather than objects. Here, we avoid using the keyword 'new' to prevent overheads.

What is the Singleton Design Pattern?

The Singleton design pattern is based on the concept of restricting the instantiation of a class to one object. Say one object needs to perform the role of a coordinator between various instances of the application that depend on a common object, we may design an application using a Singleton. Usage of Singleton patterns is common in Banking, Financial and Travel based applications where the singleton object consists of the network related information.

A singleton class may be used to instantiate an object of it, only if that object does not already exist. In case the object exists, a reference to the existing object is given. A singleton object has one global point of access to it.

An ASP.NET Web Farm is also based on the Singleton pattern. In a Web Farm, the web application resides on several web servers. The session state is handled by a Singleton object in the form of the aspnet_state.exe, that interacts with the ASP.NET worker process running on each web server. Note that the worker process is the aspnet_wp.exe process. Imagine one of the web servers shutting down, the singleton object aspnet_state.exe still maintains the session state information across all web servers in the web farm.

In .NET, in order to create a singleton, a class is created with a private constructor, and a "static readonly" variable as the member that behaves as the instance.

What are Structural Design Patterns?

A structural design pattern establishes a relationship between entities. Thus making it easier for different components of an application to interact with each other. Following are some of the commonly known structural patterns:

>>> Adapter Pattern - Interfaces of classes vary depending on the requirement.
>>> Bridge Pattern - Class level abstraction is separated from its implementation.
>>> Composite Pattern - Individual objects & a group of objects are treated similarly in this approach.
>>> Decorator Pattern - Functionality is assigned to an object.
>>> Facade Pattern - A common interface is created for a group of interfaces sharing a similarity.
>>> Flyweight Pattern - The concept of sharing a group of small sized objects.
>>> Proxy Pattern - When an object is complex and needs to be shared, its copies are made. These copies are called the proxy objects.


What are the different types of Proxy Patterns?

1 - Remote Proxy - A reference is given to a different object in a different memory location. This may be on a different or a same machine.
2 - Virtual Proxy - This kind of object is created only & only when really required because of its memory usage.
3 - Cache Proxy - An object that behaves as a temporary storage so that multiple applications may use it. For example, in ASP.NET when a page or a user control contains the OutputCache directive, that page/control is cached for some time on the ASP.NET web server.

What is a behavioral design pattern?

Behaviorial design patterns focus on improving the communication between different objects. Following are different types of behavioral patterns:
>>> Chain Or Responsibilities Pattern - In this pattern, objects communicate with each other depending on logical decisions made by a class.
>>> Command Pattern - In this pattern, objects encapsulate methods and the parameters passed to them.
>>> Observer Pattern - Objects are created depending on an events results, for which there are event handlers created.


What is the MVC Pattern (Model View Controller Pattern)?

The MVC Pattern (Model View Controller Pattern) is based on the concept of designing an application by dividing its functionalities into 3 layers. Its like a triad of components. The Model component contains the business logic, or the other set of re-usable classes like classes pertaining to data access, custom control classes, application configuration classes etc. The Controller component interacts with the Model whenever required. The control contains events and methods inside it, which are raised from the UI which is the View component.

Consider an ASP.NET web application. Here, all aspx, ascx, master pages represent the View.

The code behind files (like aspx.cs, master.cs, ascx.cs) represent the Controller.

The classes contained in the App_Code folder, or rather any other class project being referenced from this application represent the Model component.

Advantages: * Business logic can be easily modified, without affecting or any need to make changes in the UI.
* Any cosmetic change in the UI does not affect any other component.

What is the Gang of Four Design Pattern?

The history of all design patterns used in modern day applications derive from the Gang of Four (GoF) Pattern. Gang of Four patterns are categorized into 3 types:
1 - Creational
2 - Structural
3 - Behavioral

The term "Gang of Four" (or "GoF" in acronym) is used to refer to the four authors of the book Design Patterns: Elements of Reusable Object-Oriented Software. The authors are Erich Gamma, Ralph Johnson, Richard Helm and John Vlissides.

When should design patterns be used?

While developing software applications, sound knowledge of industry proven design patterns make the development journey easy and successful. Whenever a requirement is recurring, a suitable design pattern should be identified. Usage of optimal design patterns enhance performance of the application. Though there are some caveats. Make sure that there are no overheads imposed on a simple requirement, which means that design patterns should not be unnecessarily be used.

How many design patterns can be created in .NET?

As many as one can think. Design patterns are not technology specific, rather their foundation relies on the concept of reusability, object creation and communication. Design patterns can be created in any language.

Describe the Ajax Design Pattern.

In an Ajax Design Pattern, partial postbacks are triggered asyncronously to a web server for getting live data. A web application would not flicker here, and the web site user would not even come to know that a request is being sent to the web server for live data.

Such a design pattern is used in applications like Stock Market Websites to get live quotes, News Websites for live news, Sports websites for live scores etc.

Ajax

Q1 - What is AJAX?

A - Ajax stands for Asynchronous Javascript & XML. It is a web technology through which a postback from a client (browser) to the server goes partially, which means that instead of a complete postback, a partial postback is triggered by the Javascript XmlHttpRequest object. In such a scenario, web-application users won't be able to view the complete postback progress bar shown by the browser. In an AJAX environment, it is Javascript that starts the communication with the web server.
Ajax technology in a website may be implemented by using plain Javascript and XML. Code in such a scenario may tend to look little complex, for which the AJAX Framework in .NET can be embedded in ASP.NET web applications.
In addition to XML & Javascript, AJAX is also based on DOM - the Document Object Model technology of browsers through which objects of the browser can be accessed through the memory heap using their address.
JSON - Javascript Object Notation is also one of the formats used in AJAX, besides XML.
So basically, in an AJAX-based web application, the complete page does not need to reload, and only the objects in context of ajaxification are reloaded.
Ajax technology avoids the browser flickering.


Q2 - Can Ajax be implemented in browsers that do not support the XmlHttpRequest object?

A - Yes. This is possible using remote scripts.

Q3 - Can AJAX technology work on web servers other than IIS?

A - Yes, AJAX is a technology independent of web server the web application is hosted on. Ajax is a client (browser) technology.

Q4 - Which browsers support the XmlHttpRequest object?

A - Internet Explorer 5.0+, Safari 1.2, Mozilla 1.0/Firefox, Opera 8.0 +, Netscape 7

Q5 - How to we create an XmlHttpRequest object for Internet Explorer? How is this different for other browsers?

A - For Internet Explorer, an ActiveXObject is used for declaring an XmlHttpRequest object in Javascript.

//Code as below for IE:

xmlHttpObject = new ActiveXObject("Msxml2.XMLHTTP");

//For Other browsers, code as below:

xmlHttpObject = new XMLHttpRequest();



Note that XmlHttpObject used above is simply a variable that holds the XmlHttpRequest object for the respective browsers.

Q6 - What are the properties of the XmlHttpRequest object? What are the different types of readyStates in Ajax?

A - i) onreadyStateChange - This function is used to process the reply from the web server.

ii) readyState - This property holds the response status of the web server. There are 5 states:

0 - request not yet initialized

1 - request now set

2 - request sent

3 - request processing

4 - request completes

iii) responseText - Has the data sent back by the web server

Code snippet below shows an example how these there properties are used to implement ajax :

xmlHttpObject.onreadystatechange=function()
{
if(xmlHttpObject.readyState==4)
{
document.Form1.time.value=xmlHttpObject.responseText;
}
}


Q7 - What is the ASP.NET Ajax Framework? What versions have been released so far?

A - ASP.NET AJAX is a free framework to implement Ajax in asp.net web applications, for quickly creating efficient and interactive Web applications that work across all popular browsers.

The Ajax Framework is powered with

1 - Reusable Ajax Controls

2 - Support for all modern browsers

3 - Access remote services and data from the browser without tons of complicated script.

Versions of Ajax release

1 - ASP.NET Ajax Framework 1.0 (earlier release to this was called the Atlas)
2 - ASP.NET Ajax Framework 1.0 was available as a separate download for ASP.NET 2.0


Q8 - What are Ajax Extensions?

A - The ASP.NET Ajax Extensions are set of Ajax-based controls that work in ASP.NET 2 (or above) based applications.

Ofcourse,they also need the Ajax runtime which is actually the Ajax Framework 1.0.

ASP.NET Ajax Extensions 1.0 have to be downloaded to run with ASP.NET 2.0

The new ASP.NET 3.5 Framework comes with the Ajax Library 3.5 (containing the Ajax Extensions 3.5). So in order to use the latest Ajax, simply download .NET 3.5 Framework.

Summary :
ASP.NET Ajax Extensions 1.0 -> For ASP.NET 2.0
ASP.NET Ajax Extensions 3.5 -> For ASP.NET 3.5


Q9 - What is the ASP.NET Control Toolkit?

A - Besides the Ajax Framework (which is the Ajax engine) and Ajax Extensions (which contain the default Ajax controls), there is a toolkit called the Ajax Control Toolkit available for use & download (for free). This is a collection of rich featured, highly interactive controls, created as a joint venture between Microsoft & the Developer Community.

Q10 - What is Dojo?

A - Dojo is a third-party javascript toolkit for creating rich featured applications. Dojo is an Open Source DHTML toolkit written in JavaScript. It builds on several contributed code bases (nWidgets, Burstlib, f(m)), which is why we refer to it sometimes as a "unified" toolkit. Dojo aims to solve some long-standing historical problems with DHTML which prevented mass adoption of dynamic web application development.

For more on Dojo, check this link: Click Here


Q11 - How to handle multiple or concurrent requests in Ajax?

A - For concurrent requests, declare separate XmlHttpRequest objects for each request. For example, for request to get data from an SQL table1, use something like this...



xmlHttpObject1.Onreadystatechange = functionfromTable1();

and to get data from another table (say table2) at the same time, use

xmlHttpObject2.Onreadystatechange = functionfromTable2();

Ofcourse, the XmlHttpObject needs to be opened & parameters passed too, like as shown below...

xmlHTTPObject1.open("GET","http://"localhost// " + "Website1/Default1.aspx" true);

Note that the last parameter "true" used above means that processing shall carry on without waiting for any response from the web server. If it is false, the function shall wait for a response.

Q12 - How to create an AJAX website using Visual Studio?

A - Using Visual Studio Web Developer Express 2005 & versions above it, Ajax based applications may easily be created. Note that the Ajax Framework & Ajax Extensions should be installed (In case of VS 2005). If using Visual Studio 2008 Web Developer Express or above, Ajax comes along with it (so no need of a separate installation).

Steps: Start Visual Studio, Click on File -> New Website -> Under Visual Studio Installed templates -> Select ASP.NET Ajax-Enabled Site. Enter a location & select OK.

Q13 - What is the role of ScriptManager in Ajax?

A - ScriptManager class is the heart of ASP.NET Ajax. Before elaborating more on ScriptManager, note that ScriptManager is class and a control (both) in Ajax.

The ScriptManager class in ASP.NET manages Ajax Script Libraries, partial page rendering functionality and client proxy class generation for web applications and services. By saying client proxy class, this means an instance of the Ajax runtime is created on the browser.

This class is defined in the System.Web.Extensions.dll. You will find this DLL in your system's Global Assembly Cache at C:\Windows\Assembly (For XP)

The ScriptManager control (that we may drag on a web form) is actually an instance of the ScriptManager class that we put on a web page. The ScriptManager manages all the ASP.NET Ajax controls on a web page. Following tasks are taken care by the ScriptManager class:
1 - Managing all resources (all objects/controls) on a web page
2 - Managing partial page updates
3 - Download Ajax Script Library to the client (means to the browser). This needs to happen so that Ajax engine is accessible to the browsers javascript code.
4 - Interacting with UpdatePanel Control, UpdateProgress Control.
5 - Register script (using RegisterClientScriptBlock)
6 - Information whether Release OR Debug script is sent to the browser
7 - Providing access to Web service methods from the script by registering Web services with the ScriptManager control
8 - Providing access to ASP.NET authentication, role, and profile application services from client script after registering these services with the ScriptManager control
9 - Enable culture specific display of clientside script.
10 - Register server controls that implement IExtenderControl and IScriptControl interfaces.

ScriptManager class' EnablePartialRendering property is true by default.

Q14 - Can we override the EnablePartialRendering property of the ScriptManager class?

A - Yes. But this has to be done before the init event of the page (or during runtime after the page has already loaded). Otherwise an InvalidOperationException will be thrown.

Q15 - How to use multiple ScriptManager controls in a web page?

A - No. It is not possible to use multiple ScriptManager control in a web page. In fact, any such requirement never comes in because a single ScriptManager control is enough to handle the objects of a web page.

Q16 - Whats the difference between RegisterClientScriptBlock, RegisterClientScriptInclude and RegisterClientScriptResource?

A - For all three, a script element is rendered after the opening form tag. Following are the differences:
1 - RegisterClientScriptBlock - The script is specified as a string parameter.
2 - RegisterClientScriptInclude - The script content is specified by setting the src attribute to a URL that points to a script file.
3 - RegisterClientScriptResource - The script content is specified with a resource name in an assembly. The src attribute is automatically populated with a URL by a call to an HTTP handler that retrieves the named script from the assembly.



Q17 - What are type/key pairs in client script registration? Can there be 2 scripts with the same type/key pair name?

A - When a script is registered by the ScriptManager class, a type/key pair is created to uniquely identify the script.

For identification purposes, the type/key pair name is always unique for dentifying a script. Hence, there may be no duplication in type/key pair names.

Q18 - What is an UpdatePanel Control?

A - An UpdatePanel control is a holder for server side controls that need to be partial postbacked in an ajax cycle. All controls residing inside the UpdatePanel will be partial postbacked. Below is a small example of using an UpdatePanel.















As you see here after running the snippet above, there wont be a full postback exhibited by the web page. Upon clicking the button, the postback shall be partial. This means that contents outside the UpdatePanel wont be posted back to the web server. Only the contents within the UpdatePanel are refreshed.

Q19 - What are the modes of updation in an UpdatePanel? What are Triggers of an UpdatePanel?

A - An UpdatePanel has a property called UpdateMode. There are two possible values for this property: 1) Always 2) Conditional

If the UpdateMode property is set to "Always", the UpdatePanel control’s content is updated on each postback that starts from anywhere on the webpage. This also includes asynchronous postbacks from controls that are inside other UpdatePanel controls, and postbacks from controls which are not inside UpdatePanel controls.

If the UpdateMode property is set to Conditional, the UpdatePanel control’s content is updated when one of the following is true:
1 - When the postback is caused by a trigger for that UpdatePanel control.

2 - When you explicitly call the UpdatePanel control's Update() method.

3 - When the UpdatePanel control is nested inside another UpdatePanel control and the parent panel is updated.

When the ChildrenAsTriggers property is set to true and any child control of the UpdatePanel control causes a postback. Child controls of nested UpdatePanel controls do not cause an update to the outer UpdatePanel control unless they are explicitly defined as triggers for the parent panel.

Controls defined inside a node have the capability to update the contents of an UpdatePanel.


If the ChildrenAsTriggers property is set to false and the UpdateMode property is set to Always, an exception is thrown. The ChildrenAsTriggers property is intended to be used only when the UpdateMode property is set to Conditional.

Q20 - How to control how long an Ajax request may last?

A - Use the ScriptManager's AsyncPostBackTimeout Property.

For example, if you want to debug a web page but you get an error that the page request has timed out, you may set

where the value specified is in seconds.

Q21 - What is ASP.NET Futures?

A -
ASP.NET AJAX Futures

The new release includes support for managing browser history (Back button support), selecting elements by CSS selectors or classes, and information on accessing “Astoria” Web data services. The Futures (July 2007) release adds:

History support for the Safari browser, inclusion of “titles”, encoding and encrypting of server-side history state and the ability to handle history in the client without a server requirement.

CSS Selectors APIs have been modified to be applicable to W3C recommendations.

A script resource extraction tool that allows you to create script files on disk that originate from embedded resources in assemblies. Important: this version of the browser history feature is now outdated and should not be used. Instead, please download the ASP.NET 3.5 Extensions Preview, which contains the new version.

For More: Click Here


Q22 - What are limitations of Ajax?

A - 1) An Ajax Web Application tends to confused end users if the network bandwidth is slow, because there is no full postback running. However, this confusion may be eliminated by using an UpdateProgress control in tandem.
2) Distributed applications running Ajax will need a central mechanism for communicating with each other

Q23 - How to make sure that contents of an UpdatePanel update only when a partial postback takes place (and not on a full postback)?

A - Make use of ScriptManager.IsInAsyncPostBack property (returns a boolean value)

Q24 - How to trigger a postback on an UpdatePanel from Javascript?

A - Call the __doPostBack function. ASP.NET runtime always creates a javascript function named __doPostBack(eventTarget, eventArgument) when the web page is rendered. A control ID may be passed here to specifically invoke updation of the UpdatePanel.

Q25 - Which request is better with AJAX, Get or Post?

A - AJAX requests should use an HTTP GET request while retrieving data where the data does not change for a given URL requested. An HTTP POST should be used when state is updated on the server. This is in line with HTTP idempotency recommendations and is highly recommended for a consistent web application architecture.