Showing posts with label Question & Answers. Show all posts
Showing posts with label Question & Answers. Show all posts

Thursday, 20 February 2014

AJAX

Getting Started With AJAX

This is the first installment of a new online column for Visual Studio Magazine. The column will focus on several key .NET technologies, including ASP.NET AJAX, Silverlight, XML and Web services. It'll provide short to-the-point articles from which you can quickly and easily glean information.
In this article, I'll introduce AJAX, walking you through the concepts behind it, demonstrating how it works, and explaining why you may want to use it in your ASP.NET Web sites.

What Is AJAX?

AJAX, or Asynchronous JavaScript and XML, is an acronym for many technologies, rather than a single technology. It has been around for many years. Back in the old days, you could implement AJAX principles by using remote scripting (which relied on a Java Applet), the Internet Explorer 5 Web Service Behavior (which relied on JavaScript and the XMLHttpRequest object), or IFrames.


Today, most Web applications send data to a server by performing postback operations that reload the entire page. For example, if you click on a button or select an item from a drop-down list, you will see the page reload, even though you may have only requested a small amount of new information.

When Internet Explorer 5 was released, it enabled you to build Web applications that sent requests to the server without requiring full postback operations and page reloads. Instead, you could use it for "partial page updates" or updates to specific parts of a page. Partial page updates offered better performance times and created happier end users.

All modern browsers (including Internet Explorer, FireFox, Safari and Opera) provide partial page updates by supporting AJAX capabilities. AJAX describes the process during which Web pages leverage JavaScript, the XMLHttpRequest and Dynamic HTML (DHTML) to make asynchronous calls to a server and update parts of a page when a response is received. Asynchronous AJAX calls are one or more calls made to a server while a user interacts with a browser that is performing other actions. Making these calls results in richer applications that look and feel more like desktop applications.

While AJAX sounds good in principle, it can be problematic to implement across multiple browsers. Internet Explorer 5 and Internet Explorer 6 rely on built-in ActiveX controls to make AJAX calls, whereas FireFox, Safari, Opera and Internet Explorer 7 use a built-in JavaScript XMLHttpRequest object. To write cross-browser AJAX code, you must understand JavaScript and the different ways browsers can call a server asynchronously.

Listing 1 shows a simple example of how you can make a cross-browser AJAX call to add two numbers and show the result. As you look through the code in Listing 1, you'll see that the GetXmlHttp() function performs several checks to determine how to properly create the XMLHttpRequest object and use it based upon the browser. You can write this code several ways, including using try/catch blocks to load a particular XMLHttpRequest object.

XMLHttpRequest Object in Different Browsers
Listing 1. Accounting for differences in how browsers use the XMLHttpRequest object can be painful. This listing shows a simple cross-browser example of how you can make AJAX requests using the XMLHttpRequest object. The complete code for this example is available in the article's code download.

<script type="text/javascript">
    var xmlHttp = null;
    function Add()
    {
       var x = document.getElementById("txtX").value;
       var y = document.getElementById("txtY").value;
       
       //Create params string to be posted to server
       var params  = encodeURI("x=" + x + "&y=" + y);
       
       xmlHttp = GetXmlHttp("POST","XmlHttpHandler.ashx");
       xmlHttp.onreadystatechange = OnStateChange;
       xmlHttp.send(params);
    }
    
    function OnStateChange()
    {
       if (xmlHttp.readyState == 4)
       {   
           if (xmlHttp.status == 200)
           {
              document.getElementById("lblResult").innerHTML = 
                xmlHttp.responseText;
           }
       }
    }
    
    function GetXmlHttp(verb,url)
    {
       var request = null;
       //Create XmlHttpxmlHttp object
       var ua = navigator.userAgent.toLowerCase();
       if (window.XMLHttpRequest) //IE7, Safari, Mozilla
       {
           request = new XMLHttpRequest();
       }
       else //IE5, IE6
       {
           if (ua.indexOf('msie 5') == -1)
             request = new ActiveXObject("Msxml2.XMLHTTP");
           else
             request = new ActiveXObject("Microsoft.XMLHTTP");
       }
       request.open(verb.toUpperCase(),url,true);
       if (verb.toUpperCase() == "POST") 
           request.setRequestHeader("Content-type", 
             "application/x-www-form-urlencoded");
       return request;
    }
</script>

Fortunately, you can rely on one of many AJAX frameworks to avoid the complexities of writing AJAX code. Microsoft's recently released ASP.NET AJAX Extensions is a very useful framework. It can greatly simplify the amount of work you have to complete to AJAX-enable a Web page.

ASP.NET AJAX Options

Microsoft has three options for adding AJAX functionality into new or existing Web sites, all of which can be downloaded for free at http://ajax.asp.net. These options include ASP.NET AJAX Extensions, ASP.NET AJAX Control Toolkit and ASP.NET AJAX Futures.


ASP.NET AJAX Extensions provides a complete framework for working with AJAX technologies. It includes a client-side script library as well as several server-side ASP.NET controls. This framework extends existing ASP.NET functionality and provides a familiar development environment for existing ASP.NET application developers. By using the framework, you can AJAX-enable new or existing Web sites with limited understanding of JavaScript and the XMLHttpRequest object.

With the ASP.NET AJAX Control Toolkit, Microsoft released over 30 AJAX-enabled ASP.NET server controls. These controls can perform a variety of AJAX functions, including showing specialized modal pop-ups, reordering lists using drag-and-drop functionality, adding watermarks to textboxes, providing hover menus and more. The toolkit controls are available in a single assembly that can be dropped into your ASP.NET application's bin folder.

Finally, for those of you who like to stay on the cutting edge, Microsoft has also released ASP.NET AJAX Futures. This download contains future AJAX technologies that aren't officially supported in production environments yet. If you're interested in seeing what may be coming, then you can try out this release, but keep in mind that its documentation is limited at this point.


While AJAX is only an acronym, the technologies it references provide a great way to enhance new or existing Web sites, making them more rich, user-friendly and efficient. AJAX can be difficult to implement across different browsers, but AJAX frameworks, such as ASP.NET AJAX, are available to ease the development process. In the next column, I'll show you how to get started using the ASP.NET AJAX Extensions. 

LINQ Questions & Answers

What is Language Integrated Query (LINQ)?

LINQ is a programming model that is the composition of general-purpose standard query operators that allow you to work with data, regardless of the data source in any .NET based programming language. It is the name given to a set of technologies based on the integration of query capabilities into any .NET language.


What are LINQ query expressions?

A LINQ query, also known as a query expression, consists of a combination of query clauses that identify the data sources for the query. It includes instructions for sorting, filtering, grouping, or joining to apply to the source data. The LINQ query expressions syntax is similar to the SQL syntax. It specifies what information should be retrieved from the data source.

Write the basic steps to execute a LINQ query.
The following are the three basic steps to execute a LINQ query:
  • Obtain the data source (The data source can be either an SQL database or an XML file)
  • Create a query
  • Execute the query
Write the basic syntax of a LINQ query in Visual Basic as well as in C#.
In Visual Basic, the basic syntax of a LINQ query starts with the From clause and ends with the Select or Group By clause. In addition, you can use the Where, Order By, and Order By Descending clauses to perform additional functions, such as filtering data and generating the data in a specific order.

In C#, the basic syntax of a LINQ query starts with the From clause and ends with the Select or group by clause. In addition, you can use the where, orderby, and Orderby descending clauses to perform additional functions, such as filtering data and generating the data in a specific order.



In which statement the LINQ query is executed?

A LINQ query is executed in the For Each statement in Visual Basic and in the foreach statement in C#.

In LINQ, lambda expressions underlie many of the standard query operators. Is it True or False?

It is true.

What is PLINQ?

PLINQ stands for Parallel Language Integrated Query. It is the parallel implementation of LINQ, in which a query can be executed by using multiple processors. PLINQ ensures the scalability of software on parallel processors in the execution environment. It is used where data grows rapidly, such as in telecom industry or where data is heterogeneous.

PLINQ also supports all the operators of LINQ. In addition, you can query 'collections by using PLINQ. It can also run several LINQ queries simultaneously and makes use of the processors on the system. Apart from this, PLINQ uses parallel execution, which helps in running the queries quickly. Parallel execution provides a major performance improvement to PLINQ over certain types of legacy code, which takes too much time to execute.



What are the different Visual Basic features that support LINQ?

Visual Basic includes the following features that support LINQ:
  • Anonymous types - Enables you to create a new type based on a query result.
  • Implicitly typed variables - Enables the compiler to infer and assign a type when you declare and initialize a variable.
  • Extension method - Enables you to extend an existing type with your own methods without modifying the type itself.
What is the function of the DISTINCT clause in a LINQ query?

The DISTINCT clause returns the result set without the duplicate values.


What is the DataContext class and how is it related to LINQ?

After you add a LINQ to SQL Classes item to a project and open the O/R Designer, the empty design surface represents an empty DataContext class ready to be configured. The DataContext class is a LINQ to SQL class that acts as a conduit between a SQL Server database and the LINQ to SQL entity classes mapped to that database. This class contains the connection string information and the methods for connecting to a database and manipulating the data in the database. It is configured with connection information provided by the first item that is dragged onto the design surface.


What is the difference between the Take and Skip clauses?

The Take clause returns a specified number of elements. For example, you can use the Take clause to return two values from an array of numbers. The Skip clause skips the specified number of elements in the query and returns the rest. For example, you can use the Skip clause to skip the first four strings in an array of strings and return the remaining array of string.

What is Object Relational Designer (0/R Designer)?

The 0/R Designer provides a visual design surface to create LINQ to SQL entity classes and associations (relationships) that are based on objects in a database.


Which interface implements the standard query operators in LINQ?

The standard query operators implement the IEnumerable<T> or the IQueryable<T> interface in C# and the IEnumerable(Of T) or the IQueryable(Of T) interface in Visual Basic.


What are standard query operators in LINQ?

The standard query operators in LINQ are the extension methods that form the LINQ pattern. These operators form an API that enables querying of any .NET array or collection. It operates on sequences and allows you to perform operations, such as determining if a value exists in the sequence and performing an aggregated function, such as a summation over a sequence.


On what parameter does the GroupBy clause group the data?

The GroupBy clause groups the elements that share a common attribute.


What is a LinqDataSource control?

The LinqDataSource control enables you to use LINQ. in an ASP.NET Web page by setting the properties in the markup text. You can use the control retrieve or modify data. It is similar to the SqIDataSource and ObjectDataSource controls in the sense that it can be used to declaratively bind other ASP.NET controls on a page to a data source. The difference is that instead of binding directly to a database or to a generic class, the LinqDataSource control is designed to bind a LINQ enabled data model.


How can you open the O/R Designer?

You can open the O/R Designer by adding a new LINQ to SQL Classes item to a project.


The standard query operators are themselves a set of extension methods that provide the LINQ query functionality for any type that implements the IEnumerable<T> interface in Visual Basic. Is it True or False?

False, as it implements the IEnumerable(T) interface in Visual Basic and the IEnumerable<T> interface is implemented in C#.


What are lambda expressions in LINQ?

A lambda expression is a function without a name that calculates and returns a single value. All lambda expressions use the lambda operator =>, which read as goes to. The left side of the lambda operator specifies the input parameters and the right side holds the expression or statement block.


Before you query a DataSet object by using LINQ to DataSet, you must first populate the dataset How can you do this?

You can load the data into the dataset by using different methods, such as:
  • Using the DataAdapter class
  • Using LINQ to SQL
What are the different implementations of LINQ?

The different implementations of LINQ are:
  • LINQ to SQL - Refers to a component of.NET Framework version 3.5 that provides a run-time infrastructure to manage relational data as objects.
  • LINQ to DataSet - Refers to a component that makes it easier and faster to query over data cached in a DataSet object.
  • LINQ to XML - Provides an in-memory XML programming interface.
  • LINQ to Objects - Refers to the use of LINQ queries with any IEnumerable or IEnumerable(T) collection directly, without the use of an intermediate LINQ provider or API, such as LINQ to SQL or LINQ to XML.
Which command-line tool generates code and mapping for the LINQ to SQL component of .NET Framework?

The SqlMetal.exe command-line tool generates code and map the LINQ to SQL component.

Name the control that exposes the LINQ features to Web developers through the ASP.NET data-source control architecture.

The LinqDataSource control exposes the LINQ features to Web developers through the ASP.NET data-source control architecture.

What is the difference between the Select clause and SelectMany() method in LINQ?

Both the Select clause and SelectMany() method are used to produce a result value from a source of values. The difference lies in the result set. The Select clause is used to produce one result value for every source value. The result value is a collection that has the same number of elements from the query. In contrast, the SelectMany() method produces a single result that contains a concatenated collection from the query.

Which extension method do you need to run a parallel query in PLINQ?

The AsParallel extension method is required to run a parallel query in PLINQ.





















Increase MVC Application Performace

A compiled list of possible sources of improvement are below:
General
·         Make use of a profiler to discover memory leaks and performance problems in your application. personally I suggest dotTrace
·         Run your site in Release mode, not Debug mode, when in production, and also during performance profiling. Release mode is much faster. Debug mode can hide performance problems in your own code.
Caching
·         Use CompiledQuery.Compile() recursively avoiding recompilation of your query expressions
·         Cache not-prone-to-change content using OutputCacheAttribute to save unnecessary and action executions
·         Use cookies for frequently accessed non sensitive information
·         Utilize ETags and expiration - Write your custom ActionResult methods if necessary
·         Consider using the RouteName to organize your routes and then use it to generate your links, and try not to use the expression tree based ActionLink method.
·         Consider implementing a route resolution caching strategy
·         Put repetitive code inside your PartialViews, avoid render it xxxx times: if you end up calling the same partial 300 times in the same view, probably there is something wrong with that. Explanation And Benchmarks
Routing
·         Use to Url.RouteUrl("User", new { username = "joeuser" }) to specify routes. ASP.NET MVC Perfomance by Rudi Benkovic
·         Cache route resolving using this helper UrlHelperCached ASP.NET MVC Perfomance by Rudi Benkovic
Security
·         Use Forms Authentication, Keep your frequently accessed sensitive data in the authentication ticket
DAL
·         When accessing data via LINQ rely on IQueryable
·         Profile your queries i.e. Uber Profiler
·         Consider second level cache for your queries and add them an scope and a timeout i.e. NHibernate Second Cache
Load balancing
·         Utilize reverse proxies, to spread the client load across your app instance. (Stack Overflow uses HAProxy (MSDN).
·         Use Asynchronous Controllers to implement actions that depend on external resources processing.
Client side
·         Optimize your client side, use a tool like YSlow for suggestions to improve performance
·         Use AJAX to update components of your UI, avoid a whole page update when possible.
·         Consider implement a pub-sub architecture -i.e. Comet- for content delivery against reload based in timeouts.
·         Move charting and graph generation logic to the client side if possible. Graph generation is a expensive activity. Deferring to the client side your server from an unnecessary burden, and allows you to work with graphs locally without make a new request (i.e. Flex charting, jqbargraph, MoreJqueryCharts).
·         Use CDN's for scripts and media content to improve loading on the client side (i.e. Google CDN)
·         Minify -Compile- your JavaScript in order to improve your script size
·         Keep cookie size small, since cookies are sent to the server on every request.
Global configuration
·         If you use Razor, add the following code in your global.asax.cs, by default, Asp.Net MVC renders with an aspx engine and a razor engine. This only uses the RazorViewEngine.
ViewEngines.Engines.Clear(); ViewEngines.Engines.Add(new RazorViewEngine());
·         Add gzip (HTTP compression) and static cache (images, css, ...) in your web.config <system.webServer> <urlCompression doDynamicCompression="true" doStaticCompression="true" dynamicCompressionBeforeCache="true"/> </system.webServer>
·         Remove unused HTTP Modules
·         Flush your HTML as soon as it is generated (in your web.config) and disable viewstate if you are not using it <pages buffer="true" enableViewState="false">



Use Sprites : Sprites is a great thing to reduce request, you merge all your images into a single one and use css to get to good part of the sprite, Microsoft provides a good library to do it : Sprite and Image Optimization Preview 4.
Cache Your server object : If you have some references lists or datas which will change rarely, you can cache them into memory instead of querying database everytime.
Use ADO.Net instead of Entity Freamework : EF4 or EF5 are great to reduce developement time but it will be painfull to optimize. It's more simple to optimize a stored procedure than Entity Framework. So you should use Store procedure as much as possible. Dapper provides a simple way to query and map SQL with very good performance.
Cache Page or partial page: MVC Provides some easy filter to cache page according to some parameters, so use it.
Reduce Database calls: You can create a unique Database Request that return multiple object, check on Dapper website.
Always have a clean architecture: Have a clean n-tiers architecture, even on small project. It will help you to keep your code clean and it will be easier to optimize it if needed.

You can take a look at this template "Neos-SDI MVC Template" which will create for you a clean architecture with lots of performance improvements by default (check MvcTemplate website).

AJAX

How Ajax Works

At the heart of Ajax is the ability to communicate with a Web server asynchronously without taking away the user’s ability to interact with the page. The XMLHttpRequest is what makes this possible. Ajax makes it possible to update a page without a refresh.

What are Common Steps that AJAX Application Follows

The JavaScript function handEvent() will be invoked when an event occurred on the HTML element. In the handEvent() method, an instance of XMLHttpRequest object is created.

How Ajax Works in the Code

our DOM object is (input type="text" id="lblTime") which we have to refresh without refreshing the whole page. This will be done when we press the event of a button, i.e. onclick.

What is Ajax
Ajax (Asynchronous Javascript and XML ) is a technology used to load or retrieve the data from server without reloading or refreshing the Web page. Its a very good option in programming.
Example of Ajax

Google uses this ajax in each and every page. 
For example if you type some words in Google search box it shows some list of suggestion keywords. Listen how Google dynamically displaying the data when a user types in it, without reloading or refreshing the page?. 


Browser Support for AJAX?

Ajax can run in all type of browsers but their is a conflict in older (IE 5 and IE 6), and newer browsers (Mozilla, Netscape, IE 8, Chrome, Safari, Opera).
It can be rectified by checking the older and newer browser and implementing the below code.
For New Browsers: xmlhttp=new XMLHttpRequest();
For older Browsers: xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");


ASP.NET Question

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

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

The latter one allows you to write formatted output.

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

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

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

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

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

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

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

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

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

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

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

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

Server.Transfer is used to post a form to another page. Response.Redirect is used to redirect the user to another page or site.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


OOP Questions & Answers

Q. What is Object Oriented Programming?
A. Object-oriented programming (OOP) is a programming paradigm using “objects” (data structures consisting of data fields and methods together with their interactions) to design applications and computer programs.

Q. What is an Object?
A. An object is an instance of a class.

Q. What is a Class?
A class is the blueprint from which the individual objects are created. Class is composed of three things: a name, attributes, and operations.

Q. What is Encapsulation ?
Encapsulation implies that the non-essential details of an object are hidden from the user and an access its provided to its essential details.
Example : Computer games also use this feature. The user only needs to know how to play the game, the complex working of the game is hidden from the user.
Encapsulation is the feature that provides security to the data and the methods of a class.

Q. What is Abstraction ?
Abstraction is a process of hiding unwanted details from the user.
Abstraction also means ignoring the non-essential details of an object and concentrating on its essential details.

Q. What is Inheritance ?
Inheritance enables you to extend the functionality of an existing class.
When you create a class that inherits another existing class, it will inherit the attributes and behavior of that class, plus it can also have new attributes and behavior that are specific to that class.
Advantage : Code-Resuability which result in saving time and energy.

Q. What is Polymorphism ?
Polymorphism – Poly stands for many and morph means form. So any thing that exists in more than one form is known as polymorph.
In oops, polymorphism means assigning a different meaning to an entity in different context.

Q. What are the different types of Inheritance ?
There are 5 types of inheritance,
a. Single Inheritence – One Super Class and One Sub class.
b. Multiple Inheritance – More than One Super Class and One Sub class
c. Multi Level Inheritance – A Class which is a Sub class of One class, becomes a Super class for another class.
d. Hierarchical Inheritance – One Super Class and many Sub classes
e. Hybrid Inheritance – Multiple and Multi level combined.

Q. What are the different types of Polymorphism ?
There are two types of polymorphism
1. Run Time Polymorphism
2. Compile time Polymorphism

To achive the Compile Time polymorphism there two ways

Function Overloading
Operator Overloading

To achieve the Run time Polymorphism we need to use

Virtual functions

Q. What is a Virtual Function ?
Virtual functions are normal member functions of a class, which can be over-ridden in the derived classes. The whole functionality can be replaced in the over-riding function.
In C#, the virtual functions will be declared with a keyword ‘virtual’ and the over-riding functions will be declared with ‘override’ key word.

Q. What is Serialization and De-Serialization?
Serialization is the process of converting an object into a series of bytes for transmitting or storing purpose. Deserialization is a process, where these same bytes are converted back into objects.

Q. What is an Abstract Class ?
Abstract class is a class which cannot be instantiated but it is inherited by derived classes. This class contains abstract as well as non-abstract methods and members.
Any concrete class (i.e not abstract) inheriting an abstract class MUST implement ALL inherited abstract method.

Q. What is an Interface ?
Interface is a contract for what a class MUST do, but it does not specify the way it should be done.
An interface contains only the signatures of methods (only the declaration). A class implementing the interface must implement all the members of the interface (i.e provide the definations for those methods).
Interface separates the implementation and defines the structure, and this concept is very useful in cases where you need the implementation to be flexible.
Interfaces can inherit other (many) Interfaces.
A Class can implement many Interfaces.

Q. What is the difference between Abstract class and Interface ?
An abstract class can have abstract members as well non abstract members. But in an interface all the members are implicitly abstract and all the members of the interface must be overriden in its derived class.
A class can inherit one or more interfaces, but only one abstract class.
An abstract class can have 0 abstract method.
Abstract class can have fields (such as int, string etc) , whereas Interface cannot.

Q. What are the different accessibility levels that can be defined in .NET?
Private – Only members of class have access.
Protected – All members in current class and in derived classes can access the variables.
Friend (internal in C#) – Only members in current project have access to the elements.
Protected friend (protected internal in C#) – All members in current project and all
members in derived class can access the variables.
Public – All members have access in all classes and projects.

Q. What is the difference between Class and Structure?
Structs are value types and classes are reference types. The general different is that a reference type lives on the heap, and a value type lives inline, that is, wherever it is your variable or field is defined.
A struct’s members are public by default while a class’ members are private by default
Classes are reference types and structs are value types.

Q. What does virtual keyword mean?
A. It signifies that the method/property can be overridden.

Q. What are static variables?
A static member cannot be referenced through an instance. Instead it is referenced through the class name.

An instance of a class will contain a separate copy for each instance, whereas for static, there will be only one copy for each static field.

If static keyword is applied to a class then all members of the class must be static.

Q. What is Finalize method in .NET?
Allows an object to try and free resources and perform other clean up operations before it is reclaimed by garbage collection.

Q. What is Dispose method in .NET?
Dispose method belongs to ‘IDisposable’ interface. If any object wants to release its unmanaged code, it is a good practice to implement the ‘IDisposable’ interface and then override the Dispose() method.

Q. What is the use of “Overrides” and “Overridable” keywords?
Overridable is used in parent class to indicate that a method can be overridden. Overrides is used in the child class to indicate that you are overriding a method

Q. Where are all .NET Collection classes located?
System.Collection namespace

Q. What is an ArrayList?
An ArrayList is a data structure. It stores data in an array that can be dynamically resized. Array list can hold item of different types. You can access any item in array using the INDEX value of the array position.

Q. What is a HashTable?
Hashtable optimizes lookups. This type is used in the C# language. It computes a hash of each key you add. It then uses this hash code to look up the element very quickly. It is an older .NET Framework type. It is slower than the generic Dictionary type.
Code:
Hashtable hashtable = new Hashtable();
hashtable[1] = "One";
hashtable[2] = "Two";
hashtable[13] = "Thirteen";

foreach (DictionaryEntry entry in hashtable)
{
Console.WriteLine("{0}, {1}", entry.Key, entry.Value);
}

Q. What are Collections in .NET
List
First, the List type provides you with an efficient and dynamically-allocated array. It does not provide fast lookup in the general case, which you will want to use Dictionary for. It is excellent when used in loops.
Code:
// Use the List type.
List<string> list = new List<string>();
list.Add("cat");
list.Add("dog");

foreach (string element in list)
{
Console.WriteLine(element);
}

Dictionary
The Dictionary type in the base class library is one of the most important ones you need to use for your C# programs. It is an implementation of a hashtable, which is an extremely efficient way to store keys for lookup. The Dictionary in .NET is well-designed.
Code:
// Use the dictionary.
Dictionary<string, int> dict = new Dictionary<string, int>();
dict.Add("cat", 1);
dict.Add("dog", 4);

Console.WriteLine(dict["cat"]);
Console.WriteLine(dict["dog"]);

ArrayList
As shown in this program, the ArrayList is a collection found in System.Collections and it can store objects of any derived type. You don’t need to worry about the type of the elements, at least until you need to know their types to use them.
Code:
ArrayList list = new ArrayList();
list.Add("cat");
list.Add(2);
list.Add(false);

foreach (var element in list)
{
Console.WriteLine(element);
}

Hashtable
Hashtable optimizes lookups. This type is used in the C# language. It computes a hash of each key you add. It then uses this hash code to look up the element very quickly. It is an older .NET Framework type. It is slower than the generic Dictionary type. First, you can create a new Hashtable with the simplest constructor. When it is created, the Hashtable has no values. We directly assign values with the indexer, which uses the square brackets [ ]. The example adds three integer keys with one string value each.
Code:
Hashtable hashtable = new Hashtable();
hashtable[1] = "One";
hashtable[2] = "Two";
hashtable[13] = "Thirteen";

foreach (DictionaryEntry entry in hashtable)
{
Console.WriteLine("{0}, {1}", entry.Key, entry.Value);
}

Stack
Stack is a LIFO collection. It provides a powerful and simple last-in-first-out data structure. This can help you develop parsers quickly and also replace complex recursive algorithms. Stack is a generic type.

LIFO:
The last element added (with Push) to Stack is the first one removed (with Pop).
Code:
Stack<int> stack = new Stack<int>();
stack.Push(100);
stack.Push(1000);
stack.Push(10000);
return stack;

Queues
Queue is a FIFO collection. It helps when you have elements that you need to process in a first-in, first-out order. It processes the elements that you received longest ago first. We look at several examples of using Queue<T>. We think about some of the logic used for processing help requests in a C# application.

First-In-First-Out:
The queue data structure implements this algorithm. Queue is a generic type with one type parameter.
Code:
// New Queue of integers
Queue<int> q = new Queue<int>();

q.Enqueue(5); // Add 5 to the end of the Queue.
q.Enqueue(10); // Then add 10. 5 is at the start.
q.Enqueue(15); // Then add 15.
q.Enqueue(20); // Then add 20.


Q. What is an ENUM?
It is used to define constants. Enums store special values. They make programs simpler. If you place constants directly where used, your C# program becomes complex. It becomes hard to change. Enums instead keep these magic constants in a distinct type. They improve code clarity. They alleviate maintenance issues.
An enum type is a distinct value type that declares a set of named constants.

Q. What is a nested Classes?
Nested classes are classes within classes. In sample below “ClsNested” class has a “Child
Nested” class nested inside it.

The class B here is enclosed inside the declaration of class A. Class B is thus a nested class. Because it has a public accessibility modifier, it can be accessed in places other than class A’s scope. In the main entry point, we create an instance of A, and also an instance of A.B. The instance of A does not contain an instance of B; the reverse is also the case.

Program that shows nested class B [C#]

class A
{
public int _v1;
Code:
public class B
{
public int _v2;
}
}

class Program
{
static void Main()
{
A a = new A();
a._v1++;

A.B ab = new A.B();
ab._v2++;
}
}

Q. What is Operator overloading in .NET?
It provides a way to define and use operators such as +, -, and / for user-defined classes or
structs. It allows us to define/redefine the way operators work with our classes and structs. This allows programmers to make their custom types look and feel like simple types such as int and string.
Code:
using System;

class Widget
{
public int _value;

public static Widget operator +(Widget a, Widget b)
{
// Add two Widgets together.
// … Add the two int values and return a new Widget.
Widget widget = new Widget();
widget._value = a._value + b._value;
return widget;
}

public static Widget operator ++(Widget w)
{
// Increment this widget.
w._value++;
return w;
}
}

class Program
{
static void Main()
{
// Increment widget twice.
Widget w = new Widget();
w++;
Console.WriteLine(w._value);
w++;
Console.WriteLine(w._value);

// Create another widget.
Widget g = new Widget();
g++;
Console.WriteLine(g._value);

// Add two widgets.
Widget t = w + g;
Console.WriteLine(t._value);
}
}

Output
Quote:1
2
1
3


Q. What is the significance of Finalize method in .NET?
For the majority of the objects that your application creates, you can rely on the .NET Framework’s garbage collector to implicitly perform all the necessary memory management tasks. However, when you create objects that encapsulate unmanaged resources, you must explicitly release the unmanaged resources when you are finished using them in your application. The most common type of unmanaged resource is an object that wraps an operating system resource, such as a file, window, or network connection. Although the garbage collector is able to track the lifetime of an object that encapsulates an unmanaged resource, it does not have specific knowledge about how to clean up the resource. For these types of objects, the .NET Framework provides the Object.Finalize method, which allows an object to clean up its unmanaged resources properly when the garbage collector reclaims the memory used by the object. By default, the Finalize method does nothing. If you want the garbage collector to perform cleanup operations on your object before it reclaims the object’s memory, you must override the Finalize method in your class.

Q. What is the use of DISPOSE method?
Dispose method belongs to ‘IDisposable’ interface. We had seen in the previous section how bad it can be to override the finalize method for writing the cleaning of unmanaged resources. So if any object wants to release its unmanaged code best is to implement I Disposable and override the Dispose method of I Disposable interface. Now once your class has exposed the Dispose method it is the responsibility of the client to call the Dispose method to do the cleanup.

Q. In what instances you will declare a constructor to be private?
When we create a private constructor, we cannot create object of the class directly from a client.
Therefore, you will use private constructors when you do not want instances of the class to be created by any external client. Example UTILITY functions in project will have no instance and be used with out creating instance, as creating instances of the class would be waste of memory.

Q. Can two catch blocks be executed?
No, once the proper catch section is executed the control goes finally to block. So there will not be any scenarios in which multiple catch blocks will be executed.

Q. What is the difference between System.String and System.StringBuilder
System. String is immutable;
System.StringBuilder can have mutable string where a variety of operations can be performed.
Jquery Question Answers

Q1. What is Jquery in the context of web applications?
jQuery is nothing but a collection of well written JavaScript code.
In other words Jquery is ready made concise and fast JavaScript Library to be used.

Q2. What are the advantages of using jQuery over JavaScript in ASP.NET web application
Below are the advantages of using jQery over JavaScript

1.Jquery is well written optimised javascript code so it will be faster in execution unless we write same standard optimised javascript code.

2.Jquery is concise java script code ,means minimal amount of code is to be written for the same functionality than the javascript.

3.Javascript related Development is fast using Jquery because most of the functionality is already written in the library and we just need to use that.

4.Jquery has cross browser support ,so we save time for supporting all the browsers.

Q3. How to use jQuery in ASP.NET web application?
To use jQuery in ASP.NET web application follow the below steps:
a)Go to
http://jquery.com/(The official jQuery WebSite)

b)Download latest .js jQuery file from the website.

c)Put it the script(or other folder) in the root of your web application

d)Add the below tag on the page where you want to use Jquery script type="text/javascript" src="script/jQueryDownLoadedFileName.js" /script

Q4. What is the use of Jquery min js file in ASP.NET web application
JQuery min .js file is actully a minified version of Actual JQuery .js. The min files have less size but same content so this improves the performance.so You should prefer to use min files.

Q5. What is the advantages of use of document.ready functions in jQuery
Advantage of using $(document).ready(function () in jQuery is that the code inside this function will execute only when the full page has been loaded so that there will be no error like the DOM object on which the Jquery has to execute is not loaded.

Q6. Can we write more than one document.ready jQuery functions in one page
Yes we can write more than one jquery $(document).ready(function () in one page.This is helpful when you have large Jquery code and you want to split it in multiple files.

Q7. How to select an element with Id in Jquery
To select an element with Id write as below:
var divValue = $(''#sampleDivId'').val();

Q8. How to select an element with class in Jquery
To select an element with class write as below:
$(".sampleClass").css("border","2px solid blue");


Q9. What is the difference between jQuery find and children methods
The difference between find() and children() methods are that the children only travels a single level down the DOM tree while the find travels at all level down the DOM tree.

Q10. How to use length function in jQuery to text existence of an element by Id
To test if an element exists we can use length method in jQuery as below:
if $(''#mySampleDiv'').length )//Tests wheter the div with id mySampleDiv exists or not $(mySampleDiv).find(''div'');