Showing posts with label C#.Net Interview Questions. Show all posts
Showing posts with label C#.Net Interview Questions. Show all posts

Asp.net real time MVC Interview Quesitons with answers



What is MVC?
MVC is a framework methodology that divides an application’s implementation into three component roles: models, views, and controllers.
“Models” in a MVC based application are the components of the application that are responsible for maintaining state. Often this state is persisted inside a database (for example: we might have a Product class that is used to represent order data from the Products table inside SQL).
“Views” in a MVC based application are the components responsible for displaying the application’s user interface. Typically this UI is created off of the model data (for example: we might create an Product “Edit” view that surfaces textboxes, dropdowns and checkboxes based on the current state of a Product object).
“Controllers” in a MVC based application are the components responsible for handling end user interaction, manipulating the model, and ultimately choosing a view to render to display UI. In a MVC application the view is only about displaying information – it is the controller that handles and responds to user input and interaction.

What are the 3 main components of an ASP.NET MVC application?
1. M - Model
2. V - View
3. C - Controller

In which assembly is the MVC framework defined?
System.Web.Mvc

Is it possible to combine ASP.NET webforms and ASP.MVC and develop a single web application?
Yes, it is possible to combine ASP.NET webforms and ASP.MVC and develop a single web application.

What does Model, View and Controller represent in an MVC application?
Model: Model represents the application data domain. In short the applications business logic is contained with in the model.

View: Views represent the user interface, with which the end users interact. In short the all the user interface logic is contained with in the UI.

Controller: Controller is the component that responds to user actions. Based on the user actions, the respective controller, work with the model, and selects a view to render that displays the user interface. The user input logic is contained with in the controller.

What is the greatest advantage of using asp.net mvc over asp.net webforms?
It is difficult to unit test UI with webforms, where views in mvc can be very easily unit tested.

Which approach provides better support for test driven development - ASP.NET MVC or ASP.NET Webforms?
ASP.NET MVC
What is Razor View Engine?
Razor view engine is a new view engine created with ASP.Net MVC model using specially designed Razor parser to render the HTML out of dynamic server side code. It allows us to write Compact, Expressive, Clean and Fluid code with new syntaxes to include server side code in to HTML.


What are the advantages of ASP.NET MVC?
1. Extensive support for TDD. With asp.net MVC, views can also be very easily unit tested.
2. Complex applications can be easily managed
3. Seperation of concerns. Different aspects of the application can be divided into Model, View and Controller.
4. ASP.NET MVC views are light weight, as they donot use viewstate.

Is it possible to unit test an MVC application without running the controllers in an ASP.NET process?
Yes, all the features in an asp.net MVC application are interface based and hence mocking is much easier. So, we don't have to run the controllers in an ASP.NET process for unit testing.
What is namespace of asp.net mvc?
ASP.NET MVC namespaces and classes are located in the System.Web.Mvc assembly.
System.Web.Mvc namespace 
Contains classes and interfaces that support the MVC pattern for ASP.NET Web applications. This namespace includes classes that represent controllers, controller factories, action results, views, partial views, and model binders.
System.Web.Mvc.Ajax namespace 
Contains classes that support Ajax scripts in an ASP.NET MVC application. The namespace includes support for Ajax scripts and Ajax option settings.
System.Web.Mvc.Async namespace 
Contains classes and interfaces that support asynchronous actions in an ASP.NET MVC application
System.Web.Mvc.Html namespace 
Contains classes that help render HTML controls in an MVC application. The namespace includes classes that support forms, input controls, links, partial views, and validation.

Is it possible to share a view across multiple controllers?
Yes, put the view into the shared folder. This will automatically make the view available across multiple controllers.

What is the role of a controller in an MVC application?
The controller responds to user interactions, with the application, by selecting the action method to execute and alse selecting the view to render.

Where are the routing rules defined in an asp.net MVC application?
In Application_Start event in Global.asax

Name a few different return types of a controller action method?
The following are just a few return types of a controller action method. In general an action method can return an instance of a any class that derives from ActionResult class.
1. ViewResult
2. JavaScriptResult
3. RedirectResult
4. ContentResult
5. JsonResult
What is the ‘page lifecycle’ of an ASP.NET MVC?
Following process are performed by ASP.Net MVC page:
1) App initialization
2) Routing
3) Instantiate and execute controller
4) Locate and invoke controller action
5) Instantiate and render view

What is the significance of NonActionAttribute?
In general, all public methods of a controller class are treated as action methods. If you want prevent this default behaviour, just decorate the public method with NonActionAttribute.

What is the significance of ASP.NET routing?
ASP.NET MVC uses ASP.NET routing, to map incoming browser requests to controller action methods. ASP.NET Routing makes use of route table. Route table is created when your web application first starts. The route table is present in the Global.asax file.
How route table is created in ASP.NET MVC?
When an MVC application first starts, the Application_Start() method is called. This method, in turn, calls the RegisterRoutes() method. The RegisterRoutes() method creates the route table.

What are the 3 segments of the default route, that is present in an ASP.NET MVC application?
1st Segment - Controller Name
2nd Segment - Action Method Name
3rd Segment - Parameter that is passed to the action method

Example
http://nareshkamuni.blogspot.in/search/label/MVC
Controller Name = search
Action Method Name = label
Parameter Id = MVC

ASP.NET MVC application, makes use of settings at 2 places for routing to work correctly. What are these 2 places?
1. Web.Config File : ASP.NET routing has to be enabled here.
2. Global.asax File : The Route table is created in the application Start event handler, of the Global.asax file.
How do you avoid XSS Vulnerabilities in ASP.NET MVC?
Use thesyntax in ASP.NET MVC instead of usingin .net framework 4.0.

What is the adavantage of using ASP.NET routing?
In an ASP.NET web application that does not make use of routing, an incoming browser request should map to a physical file. If the file does not exist, we get page not found error.

An ASP.NET web application that does make use of routing, makes use of URLs that do not have to map to specific files in a Web site. Because the URL does not have to map to a file, you can use URLs that are descriptive of the user's action and therefore are more easily understood by users.

What are the 3 things that are needed to specify a route?
1. URL Pattern - You can include placeholders in a URL pattern so that variable data can be passed to the request handler without requiring a query string.
2. Handler - The handler can be a physical file such as an .aspx file or a controller class.
3. Name for the Route - Name is optional.

Is the following route definition a valid route definition?
{controller}{action}/{id}
No, the above definition is not a valid route definition, because there is no literal value or delimiter between the placeholders. Therefore, routing cannot determine where to separate the value for the controller placeholder from the value for the action placeholder.

What is the use of the following default route?
{resource}.axd/{*pathInfo}
This route definition, prevent requests for the Web resource files such as WebResource.axd or ScriptResource.axd from being passed to a controller.

What is the difference between adding routes, to a webforms application and to an mvc application?
To add routes to a webforms application, we use MapPageRoute() method of the RouteCollection class, where as to add routes to an MVC application we use MapRoute() method.

How do you handle variable number of segments in a route definition?
Use a route with a catch-all parameter. An example is shown below. * is referred to as catch-all parameter.
controller/{action}/{*parametervalues}

What are the 2 ways of adding constraints to a route?
1. Use regular expressions
2. Use an object that implements IRouteConstraint interface

Give 2 examples for scenarios when routing is not applied?
1. A Physical File is Found that Matches the URL Pattern - This default behaviour can be overriden by setting the RouteExistingFiles property of the RouteCollection object to true.
2. Routing Is Explicitly Disabled for a URL Pattern - Use the RouteCollection.Ignore() method to prevent routing from handling certain requests.

What is the use of action filters in an MVC application?
Action Filters allow us to add pre-action and post-action behavior to controller action methods.

If I have multiple filters impleted, what is the order in which these filters get executed?
1. Authorization filters
2. Action filters
3. Response filters
4. Exception filters
What are the different types of filters, in an asp.net mvc application?
1. Authorization filters
2. Action filters
3. Result filters
4. Exception filters

Give an example for Authorization filters in an asp.net mvc application?
1. RequireHttpsAttribute
2. AuthorizeAttribute

Which filter executes first in an asp.net mvc application?
Authorization filter


What are the levels at which filters can be applied in an asp.net mvc application?

1. Action Method
2. Controller
3. Application
[b]Is it possible to create a custom filter?[/b]
Yes

What filters are executed in the end?
Exception Filters

Is it possible to cancel filter execution?
Yes

What type of filter does OutputCacheAttribute class represents?
Result Filter

What are the 2 popular asp.net mvc view engines?
1. Razor
2. .aspx
What is difference between Viewbag and Viewdata in ASP.NET MVC?
The basic difference between ViewData and ViewBag is that in ViewData instead creating dynamic properties we use properties of Model to transport the Model data in View and in ViewBag we can create dynamic properties without using Model data.
What symbol would you use to denote, the start of a code block in razor views?
@

What symbol would you use to denote, the start of a code block in aspx views?
<%= %>

In razor syntax, what is the escape sequence character for @ symbol?
The escape sequence character for @ symbol, is another @ symbol

When using razor views, do you have to take any special steps to proctect your asp.net mvc application from cross site scripting (XSS) attacks?
No, by default content emitted using a @ block is automatically HTML encoded to protect from cross site scripting (XSS) attacks.

When using aspx view engine, to have a consistent look and feel, across all pages of the application, we can make use of asp.net master pages. What is asp.net master pages equivalent, when using razor views?
To have a consistent look and feel when using razor views, we can make use of layout pages. Layout pages, reside in the shared folder, and are named as _Layout.cshtml

What are sections?
Layout pages, can define sections, which can then be overriden by specific views making use of the layout. Defining and overriding sections is optional.

What are the file extensions for razor views?
1. .cshtml - If the programming lanugaue is C#
2. .vbhtml - If the programming lanugaue is VB

How do you specify comments using razor syntax?
Razor syntax makes use of @* to indicate the begining of a comment and *@ to indicate the end. An example is shown below.
What is Routing?
A route is a URL pattern that is mapped to a handler. The handler can be a physical file, such as an .aspx file in a Web Forms application. Routing module is responsible for mapping incoming browser requests to particular MVC controller actions.

.Net realtime Interview Questions ?

1.What are the disadvantages of Javascript?
      1.Security. Because the code executes on the users' computer, in some cases it can be exploited for malicious purposes. This is one reason some people choose to disable JavaScript.
      2.Reliance on End User. JavaScript is sometimes interpreted differently by different browsers. Whereas server-side scripts will always produce the same output, client-side scripts can be a little unpredictable. Don't be overly concerned by this though - as long as you test your script in all the major browsers you should be safe.

        2.Difference between Html and DHtml?

        DHTML:
        DHTML is the art of combining HTML, JavaScript, DOM, and CSS
        DHTML is Not a Language
        DHTML stands for Dynamic HTML.
        DHTML is NOT a language or a web standard.
        DHTML is a TERM used to describe the technologies used to make web pages dynamic and interactive.
        To most people DHTML means the combination of HTML, JavaScript, DOM, and CSS.

        HTML:
        HTML stands for Hyper Text Markup Language,HTML is not a programming language, it is a markup language, A markup language is a set of markup tags
        HTML uses markup tags to describe web pages
        HTML documents describe web pages, contain HTML tags and plain text
        HTML documents are also called web pages

        3.Difference between N-tier and 3-tier?

        3-tier:
        A 3-tier application basically resembles a system with 3 levels or tier, the first is the client tier, second is server tier and the third tier is your data tier.
        N-tier:
        N-tier application is just an extension of this in which we again split these individual tiers into different tiers and thus the name N-tier.

        4.Difference between .net 4.0 and 4.5?

        The next major release of the .NET Framework, .NET 4.5, allows you to easily use Windows 8 technologies, like Windows Runtime, directly from .NET 4.5. Accessing your data is easier than ever with support for the newest features in SQL Server and support for WebSockets. Programs are more responsive, with the AWAIT keyword, faster ASP.NET startup and an improved server Garbage Collector. .NET 4.5 incorporates key customer feedback, with the newest MEF features, support for long running workflows with State Machines, and improved HTML 5 support in ASP.NET. In this overview talk, you’ll learn about all of these technologies, and get pointers to deeper dives where you can learn more.
        5.What is the use of Ajax?

        There are a couple of reasons to use AJAX in lieu of the traditional form submission.
        1.Ajax  is very light weight: instead of sending all of the form information to the server and getting all of the rendered HTML back, simply send the data the server needs to process and get back only what the client needs to process. Light weight means fast.
        2. The second reason to use AJAX is because (as the logo in the link above makes clear) AJAX is cool.
        3. AJAX is a client side technology that uses JavaScript, the client-server interaction is very important.

        6.Difference between MVP and MVC?
        The two patterns are having much similarities compare to their differences. The both patterns are evolved on separation of concerns and both contain Views and Models.But when comes to the difference part, the major difference is the way handling the incoming request.
        In MVP, the incoming request comes to View and View is delegating it to presenter. And presenter is responsible for talk to model and update the view. Here model is completely shielding from View.
         Where as in MVC, all incoming requests are intercepting by the controller and controller is responsible for generating the correct View and Model. Here View is aware of the model

        The MVP pattern will built on ASP.Net WebForms. The WebForms development paradigm uses Viewstate. In large Web application it will cause some performance issues.
        ASP.Net MVC is new alternative frame work and it view is state less.

        7.What is Namespace?
        A Namespace in Microsoft .Net is like containers of objects. They may contain unions, classes, structures, interfaces, enumerators and delegates. Main goal of using namespace in .Net is for creating a hierarchical organization of program. In this case a developer does not need to worry about the naming conflicts of classes, functions, variables etc., inside a project.

        8.What is the use of SilverLight?

        Microsoft Silverlight is an application framework for writing and running rich Internet applications, with features and purposes similar to those of Adobe Flash. The run-time environment for Silverlight is available as a plug-in for web browsers running under Microsoft Windows and Mac OS X. While early versions of Silverlight focused on streaming media, current versions support multimedia, graphics and animation, and give developers support for CLI languages and development tools. Silverlight is also one of the two application development platforms for Windows Phone.
        9.Explain about your Project? How much time you taken to complete the project?
        10.What is your Role in your project?

        C# Interview Questions



        Does C# support multiple-inheritance?
        No.

        Who is a protected class-level variable available to?
        It is available to any sub-class (a class inheriting this class).

         Are private class-level variables inherited?

        Yes, but they are not accessible. Although they are not visible or accessible via the class interface, they are inherited.

         Describe the accessibility modifier “protected internal”.
        It is available to classes that are within the same assembly and derived from the specified base class.

         What’s the top .NET class that everything is derived from?
        System.Object.

         What does the term immutable mean?
        The data value may not be changed. Note: The variable value may be changed, but the original immutable data value was discarded and a new data value was created in memory.



         What’s the difference between System.String and System.Text.StringBuilder classes?
        System.String is immutable. System.StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed.

         What’s the advantage of using System.Text.StringBuilder over System.String?
        StringBuilder is more efficient in cases where there is a large amount of string manipulation. Strings are immutable, so each time a string is changed, a new instance in memory is created.

         Can you store multiple data types in System.Array?
        No.
         


         What’s the difference between the System.Array.CopyTo() and System.Array.Clone() ?
        The Clone() method returns a new array (a shallow copy) object containing all the elements in the original array. The CopyTo() method copies the elements into another existing array. Both perform a shallow copy. A shallow copy means the contents (each array element) contains references to the same object as the elements in the original array. A deep copy (which neither of these methods performs) would create a new instance of each element's object, resulting in a different, yet identacle object.


         How can you sort the elements of the array in descending order?
        By calling Sort() and then Reverse() methods.


         What’s the .NET collection class that allows an element to be accessed using a unique key?
        HashTable.


        What class is underneath the SortedList class?
        A sorted HashTable.


         Will the finally block get executed if an exception has not occurred?
        Yes.


         What’s the C# syntax to catch any possible exception?
        A catch block that catches the exception of type System.Exception. You can also omit the parameter data type in this case and just write catch {}.


         Can multiple catch blocks be executed for a single try statement?
        No. Once the proper catch block processed, control is transferred to the finally block (if there are any).


         Explain the three services model commonly know as a three-tier application.
        Presentation (UI), Business (logic and underlying code) and Data (from storage or other sources).


        What is the difference between login controls and Forms authentication?

        • Forms authentication can be easily implemented using login controls without writing any code.
        • Login control performs functions like prompting for user credentials, validating them and issuing authentication just as the FormsAuthentication class.
        • However, all that’s needs to be dne is to drag and drop the use control from the tool box to have these checks performed implicitly. 
        • The FormsAuthentication class is used in the background for the authentication ticket and ASP.NET membership is used to validate the user credentials. 

        What is Fragment Caching in ASP.NET?

        • Fragment caching refers to the caching of individual user controls within a Web Form. 
        • Each user control can have independent cache durations and implementations of how the caching behavior is to be applied.
        • Fragment caching is useful when you need to cache only a subset of a page. 
        • Navigation bars, header, and footers are good candidates for fragment caching. 
        Fragment caching allows to cache specific portions of the page rather than the whole page. It is done by implementing the page in different parts by creating everything in form of user controls and caching each user control individually.


        What is partial classess in .net?

        When there is a need to keep the business logic separate from the User Interface or when there is some class which is big enough to have multiple number of developers implement the methods in it, the class can be separated and written in different files as partial class.
        The keyword partial must appear in each class.
        //syntax for C#
        Public partial class MyPartialClass1
        {
                 //code
        }
        // this code could be in file1
        Public partial class MyPartialClass1
        {
                 //code
        }
        // this code could be in file2
        Partial classes allow us to divide the class definition into multiple files (physically). Logically, all the partial classes are treated as a single file by the compiler.

        Explain how to pass a querystring from an .asp page to aspx page.

        Consider the following URL:
        http:// localhost/form.aspx?param1=career&param2=ride
        This html addresses use QueryString property to pass values between pages.
        From the URL above the information obtained is:
        form.aspx: which is the destination page for your browser.
        Param1 is the first parameter, the value of which is set to career
        Param2 is the first parameter, the value of which is set to ride
        The ‘?’ marks the beginning of the QueryString
        ‘&’ is used as a separator between parameters.
        private void formButtonSubmit_Click(object sender, System.EventArgs e)
        {
        Response.Redirect("form.aspx?Param1=" +
        this.formTextfieldParam1.Text + "&Param2=" +
        this. formTextfieldParam2.Text);
        }
        The above code is a submit button event handler and it sends the values of the query string to the second page.
        The following code demonstrates how to retrieve these valus on the second page:
        private void Page_Load(object sender, System.EventArgs e)
        {
              this.form2TextField1.Text = Request.QueryString["Param1"];
              this. form2TextField2.Text = Request.QueryString["Param2"];
        }

        You can also use the following method to retrieve the parameters in the string:

        for (int i =0;i < Request.QueryString.Count;i++)
        {
                Response.Write(Request.QueryString[i]);
        }
        From HTML in asp page: <ahref="abc.aspx?qstring1=test">Test Query String</a>
        From server side code: <%response.redirect "webform1.aspx?id=11"%>


        Difference between src and Code-Behind

        With the ‘src’ attribute, the source code files are deployed and are compiled by the JIT as needed.
        Though the code is available to everyone with an access to the server (NOT anyone on the web), this method is preferred as it does away with the compilation of the DLLs.
        ‘CodeBehind’ attribute just has the VS.NET associate the code file with the aspx file. This is necessary since VS.NET automates the pre-compiling that is harder by hand.
        Due to this the ‘Src’ attribute is done away with having only a DLL to be deployed enhancing the protection level even though it can be decompiled.
        Src: is a way mention the name of the code-behind class to dynamically compile on the request for a page.
        Code-behind: is the logic written behind the UI design file. It specifies the name of the compiled file that contains the class. Code-behind attribute is only used for.Net.

        What is the difference between URL and URI?

        A URL (Uniform Resource Locator) is the address of some resource on the Web. A resource is nothing but a page of a site. There are other type of resources than Web pages, but that's the easiest conceptually.
        A URI is a unique identifier to usually a namespace.
        Though it looks like a URL but it doesn’t have to necessarily locate any resource on the web.
        URI is a generic term. URL is a type of URI.
        URI - Uniform Resource Identifier: it’s a string and its responsibility is to identify a resource by meta-information. It gives information about only one resource.
        URL - Uniform Resource Locator: identifies the resource on the net and tells it is obtainable using what protocols.

        What is the Pre-Compilation feature of ASP.NET 2.0?

        Previously, in ASP.NET, the pages and the code used to be compiled dynamically and then cached so as to make the requests to access the page extremely efficient. In ASP.NET 2.0, the pre-compilation feature is used with which an entire site is precompiled before it is made available to users.
         There is a pre-defined folder structure for enabling the pre-compilation feature:
        • App_Code: stores classes
        • App_Themes: stores CSS files, Images, etc.
        • App_Data: stores XML files, Text Files, etc.
        • App_GlobalResources: stores all the resources at global level E.g. resx files, etc
        • App_LocalResources: stores all the resources at local/Page level
        It is a process where things that can be handled before compilation are prepared in order to reduce the deployment time, response time, increase safety. It’s main aim to boost performance.
        It also helps in informing about the compilation failures.
        During development, it allows you to make changes to the web pages and reuse it using the same web browser to validate the changes without compiling the entire website.
        During deployment, it generates the entire website folder structure in the destination. All the static files are copied to the folder and bin directory would later on contain the compiled dll.

        What are ILDASM and Obfuscator in NET?

        • ILDASM (Intermediate Language Disassembler)
          De-Compilation is the process of getting the source code from the assembly.
          ILDASM is a de-compiler provided by Microsoft.
          This ILDASM converts an assembly to instructions from which source code can be obtained.
        • Obfuscated code is source code or intermediate language that is very hard to read and understand.
          An obfuscator is a medium of making a program difficult to understand.
          The way the code runs remains unaffected although the obfuscator makes it harder to hack the code and hijack the program.
        ILDASM is MSIL Disassmbler. This take a portable executable (PE), which consists of MSIL code, and creates a text file which can then be used as an input for ILASM.exe, which is MSIL assembler. ILDASM can parse any .Net dll or exe and shows information in human readable form. It displays MSIL, namespaces, types and interfaces. It's normally used to examine assemblies and understand what the assembly is capable of.
        Obfuscator is a tool to protect .Net assemblies and exe files. The tool renames all possible symbols, types, interfaces, namespaces etc into meaningless values and removes all unnecessary information. This reduces the size of the assemblies and also helps in protecting the code. It's normally used to protect the assemblies from exposing information for reverse engineering.

        What is the GAC? What problem does it solve?

        Global Assembly Cache (GAC):
        Any system that has the CLR (common language runtime) installed, has a machine-wide code cache known as GAC.
        Assemblies deployed in the global assembly cache need to have a strong name.
        The Global Assembly Cache tool (Gacutil.exe), provided by the .NET Framework SDK can be used to deploy assemblies to GAC.

        What is a Windows Service and how does its lifecycle differ from a "standard" EXE?

        A service opens before one log in. However, a standard exe can be opened after a log in only.
        Windows Service applications are long-running applications that do not have a user interface. They do not even produce any visual output.
        The user messages are written to the Windows Event Log.
        Services can run under the context of any user or a system. They are controlled by the Service Control Manager by which they can be stopped, paused, and started.

        What is serialization in .NET? What are the ways to control serialization?

        Serialization is a process of taking an object and converting into a form so that it can be transported across the network.
        The serialized data can also be stored at a location using de-serialization.
        The data contains the state of the object by which it can be reconstructed.
        Binary Serialization is a light and compact format.
        SOAP Serialization is used in web Services.
        XML Serialization provides custom serialization.

        Describe the difference between Interface-oriented, Object-oriented and Aspect-oriented programming.

        Interface oriented approach compels to develop the software based on the contract.
        Object oriented approach emphasizes on its aspects like:
        Abstraction
        Encapsulation
        Inheritance
        Polymorphism
        Cross cutting concerns cannot be implemented in object oriented programming.
        That’s not the case with aspect-oriented. However, there is a risk of system failure in this situation.

        What is the difference between XML Web Services using ASMX and .NET Remoting using SOAP?

        • XML Web services are more restricted than objects exposed over .NET Remoting.
        • XML Web services support open standards that target cross-platform use.
        • XML Web services are generally easier to create and due to the restricted nature of XML Web services, the design issues are simplified.
        • XML Web services support only SOAP message formatting, which uses larger XML text messages.
        • Communication with .NET Remoting can be faster than XML Web service communication with a binary formatter.
        • XML Web services are designed for use between companies and organizations.
        • XML Web services don't require a dedicated hosting program because they are always hosted by ASP.NET.
        • Consumers can use XML Web services just as easily as they can download HTML pages from the Internet. Thus there's no need for an administrator to open additional ports on a firewall as they work through MS-IIS and ASP.NET

        What is the JIT? What is NGEN? What are limitations and benefits of each?

        Just In Time Compiler compiles the code just before it is run.
        Due to this the code takes longer time to start however it is more efficient compilation since the compiler has more information about the target system.

        NGen is used to pre-just in time code which yields faster startup time but the compiler produces less efficient code because it has less information.

        What is the difference between Finalize() and Dispose()?

        Dispose() is called by as an indication for an object to release any unmanaged resources it has held.
        Finalize() is used for the same purpose as dispose however finalize doesn’t assure the garbage collection of an object.
        Dispose() operates determinalistically due to which it is generally preferred.

        How does the XmlSerializer work? What ACL permissions does a process using it require?

        The XmlSerializer constructor generates a pair of classes derived from XmlSerializationReader and XmlSerializationWriter by analysis of the classes using reflection.
        Temporary C# files are created and compiled into a temporary assembly and then loaded into a process.
        The XmlSerializer caches the temporary assemblies on a per-type basis as the code generated like this is expensive. This cached assembly is used after a class is created
        Therefore the XmlSerialize requires full permissions on the temporary directory which is a user profile temp directory for windows applications.

        How does the XmlSerializer work? What ACL permissions does a process using it require?

        The XmlSerializer constructor generates a pair of classes derived from XmlSerializationReader and XmlSerializationWriter by analysis of the classes using reflection.
        Temporary C# files are created and compiled into a temporary assembly and then loaded into a process.
        The XmlSerializer caches the temporary assemblies on a per-type basis as the code generated like this is expensive. This cached assembly is used after a class is created
        Therefore the XmlSerialize requires full permissions on the temporary directory which is a user profile temp directory for windows applications.

        Explain how to add controls dynamically to the form using C#.NET.

        The following code can be called on some event like page load or onload of some image or even a user action like onclick
        protected void add_button(Button button)
        {
           try
           {
                panel1.Controls.Add(button); // Add the control to the container on a page
           }
           catch (Exception ex)
           {
                 label1.Text += ex.Message.ToString();
           }
        }

        What are Extender provider components? Explain how to use an extender provider in the project.

        An extender provider is a component that provides properties to other components.
        Implementing an extender provider:
        • Use the ProvidePropertyAttribute, which specifies the name of the property that an implementer of IExtenderProvider provides to other components, attribute to specify the property provided by your extender provider.
        • Implement the provided property.
        • Track which controls receive your provided property.
        • Implement the IExtenderProvider, which defines the interface for extending properties to other components in a containe, interface.

        Describe the configuration files in .Net. What are different types of configuration files in .Net framework?

        The Machine.Config file, which specifies the settings that are global to a particular machine.
        This file is located at the following path:
        \WINNT\Microsoft.NET\Framework\[Framework Version]\CONFIG\machine.config
        The simplest way to add application-specific settings into an application configuration file is to use an application configuration file.
        The file is an XML file and contains add elements with key and value attributes.
        <?xml version="1.0" encoding="utf-8" ?>
        <configuration>
        <appSettings>
              <add key="ApplicationTitle" value="Sample Console Application" />
             <add key="ConnectionString"value="Server=localhost;Database=Northwind;Integrated Security= false;UserId=sa;Password=;" />
        </appSettings>
        </configuration>
        <authentication> The authentication section controls the type of authentication used within your Web application Windows, Forms or Passport type of authentication can be defined.
        Eg: <authentication mode="Windows" />
        <allow> or <deny> tags can be used with authorization to allow or deny access to your web application to certain users or roles,
        <authorization>
              <allow roles="Administrators,Users" />
              <deny users="*" />
        </authorization>

        Describe the accessibility modifier "protected internal" in C#.

        The Protected Internal access modifier can be accessed by:
        Members of the Assembly
        The inheriting class
        The class itself
        Its access is limited to the types derived from the defining class in the current assembly or the assembly itself.

        What is the difference between Debug.Write and Trace.Write? When should each be used?

        Debug.Write: Debug Mode, Release Mode (used while debuging a project)
        Trace.write: Release Mode (used in Released verion of Applications)

        Explain the use of virtual, sealed, override, and abstract.

        The virtual keyword enables a class to be overridden. If it has to be prevented from being overridden, then the sealed keyword needs to be used. If the keyword virtual is not used, members of the class can even then be overridden. However, its usage is advised for making the code meaningful.
        The override keyword is used to override the virtual method in the base class. Abstract keyword is used to modify a class, method or property declaration. You cannot instantiate an abstract class or make calls to an abstract method directly.
        An abstract virtual method means that the definition of the method needs to be given in the derived class.

        What benefit do you get from using a Primary Interop Assembly (PIA)?

        A primary interop assembly contains type definitions (as metadata) of types implemented with COM.
        Only a single PIA can exist, which needs to be signed with a strong name by the publisher of the COM type library.
        One PIA can wrap multiple versions of the same type library.
        A COM type library imported as an assembly can be a PIA only if it has been signed and published by the same publisher.
        Therefore, only the publisher of a type library can produce a true PIA, that can be considered as the unit of an official type definition for interoperating with the underlying COM types.

        Explain the use of static members with example using C#.NET.

        Static members are not associated with a particular instance of any class.
        They need to be qualified with the class name to be called.
        Since they are not associated with object instances, they do not have access to non-static members.
        i.e.: "this" cannot be used, which represents the current object instance.

        How to achieve polymorphism in C#.NET?

        Polymorphism is when a class can be used as more than one type through inheritance. It can be used as its own type, any base types, or any interface type if it implements interfaces.
        It can be achieved in the following ways:
        Derived class inherits from a base class and it gains all the methods, fields, properties and events of the base class.
        To completely take over a class member from a base class, the base class has to declare that member as virtual.

        What are implementation inheritance and interface inheritance?

        Implementation inheritance is achieved when a class is derived from another class in such a way that it inherits all its members.
        Interface inheritance is when a class inherits only the signatures of the functions from another class.

        How to add a ReadOnly property in C#.NET?

        Properties can be made read-only by having only a get accessor in the implementation.
        public class X
        {
                  public X(int id)
                  {
                       x_id = id;
                  }
                  public int ID
                  {
                      get
                      {
                           return x_id;
                      }
                  }
        }

        How to prevent a class from being inherited in C#.NET?

        The sealed modifier is used to prevent derivation from a class. An error occurs if a sealed class is specified as the base class of another class. A sealed class cannot also be an abstract class.

        What are generics in C#.NET?

        Generic types to maximize code reuse, type safety, and performance.
        They can be used to create collection classes.
        Generic collection classes in the System.Collections.Generic namespace should be used instead of classes such as ArrayList in the System.Collections namespace.

        What is C#.NET Generics?

        The classes and the methods can treat the values of different types uniformly with the use if generics.
        The usage of generics is advantageous as:
        • They facilitate type safety
        • They facilitate improved performance
        • They facilitate reduced code
        • They promote the usage of parameterized types
        • The CLR compiles and stores information related to the generic types when they are instantiated. (The generic type instance refers to the location in memory of the reference type to which it is bound for all the instances of the generic type.)
        Generics allow you to define type-safe data structures, without committing to actual data types. It allows writing less but more effective code. Generic provides flexibility and power but the developer needs to be responsible while using it.

        What is the use of GetCommandLineArgs() method in C#.NET?

        With GetCommandLineArgs() method, the command line arguments can be accessed.
        The value returned is an array of strings.

        What is the use of System.Environment class in C#.NET?

        The System.Environment class can be used to retrieve information like:
        command-line arguments
        the exit code
        environment variable settings
        contents of the call stack
        time since last system boot
        the version of the common language runtime.
        What is the difference between const and readonly in C#.NET? The read only can be modified by the class it is contained in. However, the const cannot

        Advantages of CLR procedure over T-SQL procedure

        • The use of the CLR procedure makes it possible to do the complex database operations without having an in-depth knowledge of T-SQL.
        • It also enables focusing the business layer towards the database in orderto increase the server performance by avoiding unnecessary server trips.
        • Also, with the help of the .NET Base Class Libraries, the complex logical operations can be effectively performed.
        • It deals with automatic garbage collection, memory management, exception handling, etc. due to which it is known as Managed Procedure.
        • The concepts of the OOP can also be applied.
        • It provides the ability to leverage the features of .NET Code Access Security (CAS) to prevent assemblies from performing certain operations.
        CLR (common language runtime): is the core of the .NET Framework and it provides the environment for all managed code. The CLR provides all the services that are needed for the code to execute, JIT compilation, exception handling etc.
        • .NET Framework allows solving complex logic operations for e.g. string manipulations, threading operations, encoding/decoding using cryptography.
        • CLR supports garbage collection, memory management, exception handling. This makes it more effective over T-SQL.
        • CLR allows the code to be more secure through code access security (CAS) to prevent assemblies from performing few processes.

        How does C#.NET Generics and C++ Templates compare?

        C# generics and templates in C++ are more or less similar syntactically.
        • C# Generic types are strong typed. C++ Templates are loosely typed.
        • C# Generic types are instantiated at the runtime. C++ templates are instantiated at the compile time.
        • C# Generic types do not permit the type parameters to have default values. C++ templates do.

        How does C# Generics and C++ Templates compare?

        C# generics are a simpler approach to parameterized types without the complexity of C++ templates In addition, C# does not attempt to provide all of the functionality that C++ templates provide.
        a. C# generics are more flexible than c++ templates.
        b. C# does not allow type parameters to have default types.
        c. Partial specialization is not supported by C# generics
        d. C# generics are simpler that C++ templates

        What is an object pool in .NET?

        An object pool is a container of objects that holds a list of other objects that are ready to be used.
        It keeps track of:
        • Objects that are currently in use
        • The number of objects the pool holds
        • Whether this number should be increased
        The request for the creation of an object is served by allocating an object from the pool.
        This reduces the overhead of creating and re-creating objects each time an object creation is required.
        It is a list of ready to use objects. Whenever a new request comes in for creating an object, then the application is served from this pool. This reduces the overhead of creating an object over and over again.

        Why is an Object Pool required?

        The request for the creation of an object is served by allocating an object from the pool.
        This reduces the overhead of creating and re-creating objects each time an object creation is required.
        To enhance performance and reduce the load of creating new objects, instead re using existing objects stored in memory pool. Object Pool is a container of objects that are for use and have already been created. Whenever an object creation request occurs, the pool manager serves the request by allocating an object from the pool. This minimizes the memory consumption and system's resources by recycling and re-using objects. When the task of an object is done, it is sent to the pool rather than being destroyed. This reduces the work for garbage collector and fewer memory allocations occur.

        How does object pooling and connection pooling differ?

        In Object pooling, you can control the number of connections.
        In connection pooling, you can control the maximum number reached.
        When using connection pooling, if there is nothing in the pool, a connection is created since the creation is on the same thread.
        In object pooling, the pool decides the creation of an object depending on whether the maximum is reached which in case if it is, the next available object is returned. However, this could increase the time complexity if the object is heavy.
        Object pooling allows you to control the number of connections being used, whereas connection pooling allows the control of maximum number reached.

        Explain how to Implement an Object Pool in C#.NET.

        using System;
        using System.Collections;
        namespace ObjectPool
        {
              class ObjQueue
              {
                   private static int maxSize = 2;
                   private static readonly Queue objPool = new Queue(maxSize);
                   public MyClass GetMyClass()
                   {
                      MyClass oMyClass;
                      if (MyClass.Counter >= maxSize && objPool.Count>0)
                           oMyClass = RetrieveFromPool();
                      else
                           oMyClass = GetNewMyClass();
                           return oMyClass;
                   }
                   private MyClass GetNewMyClass()
                   {
                       MyClass myObj = new MyClass();
                       objPool.Enqueue(myObj);
                       return myObj;
                   }
                   protected MyClass RetrieveFromPool()
                   {
                       MyClass myObj;
                       if (objPool.Count>0)
                       {
                           myObj = (MyClass)objPool.Dequeue();
                           MyClass.Counter--;
                      }
                      else
                           myObj = new MyClass();
                           return myObj;
                  }
        }
        class MyClass
        {
                  public static int Counter = 0;
                  public MyClass() { ++Counter; }
                  private string _Firstname;
                  public string Firstname
                  {
                       get { return _Firstname; }
                       set { _Firstname = value; }
                  }
        }}

        Explain how to Implement an Object Pool in C#.NET.

        Creating pool manager.
        public sealed class MyPoolManager
        {
               private Queue poolQ = new Queue();
               private Hashtable tblPool = new Hashtable();
               private static readonly object objLock = new object();
               private const int PoolSize = 10;
               private int count = 0;
               private static MyPoolManager poolManager = null;
               /// <summary>
               /// Private constructor to prevent instantiation
               /// </summary>
               private MyPoolManager()
               {
               }
            static MyPoolManager()
             {
                  poolManager = new MyPoolManager();
             }
              public static MyPoolManager Instance
              {
                   get
                   {
                        if (poolManager != null)
                        {
                             return poolManager;
                        }
                              return null;
                    }
               }
              public void CreatePoolObjects(object obj)
              {
                     object _obj = obj;
                     count = 0;
                     poolQ.Clear();
                     tblPool.Clear();
                     for (int objCounter = 0; objCounter < PoolSize; objCounter++)
                     {
                          _obj = new object();
                          lock (objLock)
                          {
                                tblPool.Add(_obj.GetHashCode(), _obj);
                                poolQ.Enqueue(_obj);
                                count++;
                           }
                      }
               }
               public bool AddObjectToPool(object obj)
               {
                    if (count == PoolSize)
                         return false;
                     lock (objLock)
                     {
                           tblPool.Add(obj.GetHashCode(), obj);
                           poolQ.Enqueue(obj);
                           count++;
                     }
                            return true;
                 }
               public object ReleaseObjectFromPool()
               {
                    if (count == 0)
                          return null;

                     lock (objLock)
                     {
                           tblPool.Remove(poolQ.Dequeue().GetHashCode());
                           count--;
                           if (poolQ.Count > 0)
                                   return poolQ.Dequeue();
                      }
                            return null;
                 }
               public object ReleaseObjectFromPool(object obj)
               {
                        if (count == 0)
                                return null;
                        lock (objLock)
                        {
                                tblPool.Remove(obj.GetHashCode());
                                count--;
                                PutInPoolAgain();
                                return obj;
                       }
               }
               private void PutInPoolAgain()
               {
                       if (poolQ.Count > 0)
                                 poolQ.Clear();

                       foreach (int key in tblPool.Keys)
                       {
                              poolQ.Enqueue(tblPool[key]);
                       }
               }
                public int CurrentObjectsInPool
                {
                       get
                       {
                            return count;
                       }
                 }
                public int MaxObjectsInPool
                {
                          get
                          {
                                  return PoolSize;
                          }
                 }
        }
        using MyPoolManager
        object obj1 = new object();
        object obj2 = new object();
        MyPoolManager poolManager = MyPoolManager.Instance;
        poolManager.AddObjectToPool(obj1);
        poolManager.AddObjectToPool(obj2);
        MessageBox.Show(poolManager.CurrentObjectsInPool.ToString());
        poolManager.ReleaseObjectFromPool(obj1);
        MessageBox.Show(poolManager.CurrentObjectsInPool.ToString());
        object obj = null;
        for(;;)
        {
               obj = poolManager.ReleaseObjectFromPool();
               if(obj != null)
                    MessageBox.Show(obj.GetHashCode().ToString());
               else
               {
                    MessageBox.Show("No more objects in the pool");
                    break;
               }
        }

        Describe the three major components that make up a Web Service.

        • SOAP (Simple Object Access Protocol)
        • UDDI (Universal Description, Discovery and Integration)
        • WSDL (Web Services Description Language)
        • XML – provides a standard way to interact and provide language neutral format exchanging data.
        • WSDL – it describes the web service
        • UDDI – Universal Description Discovery and Integration- Interface to fetch web service data.

        Explain with code sample how to Implement a Web Service in .NET

        Following is a VBScript example
        "WebMethod()" converts the functions in your application into web services
        Example:
        <%@ WebService Language="VBScript" Class="KmToMConvert" %>
        Imports System
        Imports System.Web.Services
        Public Class KmToMConvert :Inherits WebService
           <WebMethod()> Public Function KilometerToMeter(ByVal Kilometer As String) As String
                 return (Kilometer * 1000)
                 end function
        end class
        [WebService(Namespace = http://tempuri.org/)]
        [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
        [System.ComponentModel.ToolboxItem(false)]
        // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
        // [System.Web.Script.Services.ScriptService]
        public class Service1 : System.Web.Services.WebService
        {
             [WebMethod]
             public string HelloWorld()
             {
                    return "Hello World";
             }
        }

        What are ILDASM and Obfuscator in NET?

        • ILDASM (Intermediate Language Disassembler)
          De-Compilation is the process of getting the source code from the assembly.
          ILDASM is a de-compiler provided by Microsoft.
          This ILDASM converts an assembly to instructions from which source code can be obtained.
        • Obfuscated code is source code or intermediate language that is very hard to read and understand.
          An obfuscator is a medium of making a program difficult to understand.
          The way the code runs remains unaffected although the obfuscator makes it harder to hack the code and hijack the program.
        ILDASM is MSIL Disassmbler. This take a portable executable (PE), which consists of MSIL code, and creates a text file which can then be used as an input for ILASM.exe, which is MSIL assembler. ILDASM can parse any .Net dll or exe and shows information in human readable form. It displays MSIL, namespaces, types and interfaces. It's normally used to examine assemblies and understand what the assembly is capable of.
        Obfuscator is a tool to protect .Net assemblies and exe files. The tool renames all possible symbols, types, interfaces, namespaces etc into meaningless values and removes all unnecessary information. This reduces the size of the assemblies and also helps in protecting the code. It's normally used to protect the assemblies from exposing information for reverse engineering.

        Explain how Obfuscator works.

        • Obfuscators protect the source code from being hacked. Encryption and Decryption are processes from where you can get the data back.
        • However these differ from what obfuscation is. In obfuscation, a program become out of the reach of hackers although it functions the same way it is supposed to.
        • Optimizations too get applied to the process of obfuscation in order to make the program fast.
        Obfuscator simply renames all types and namespace etc to meaningless code making it non human readable. This diminishes the possibility of reverse engineering.
        e.g.:
        private void AddEmp(Employee employee)
        {
           {
              this.EmpList.Add(employee);
           }
        }
        gets converted to
        private void a(a b)
        {
            {
              a.a.Add(b);
            }
        }

         

        What are delegates and why are they required?

        The delegates in .NET are like the pointers to the functions in C/C++. The difference is that these are type safe unlike the once in C/C++.
        There are situations where in a programmer or an application needs to perform an action on a particular event. Eg: Some user action like click, text change, etc. So when these actions are performed by the user, the delegates invoke the respective functions.
        Delegates are like type safe function pointers. We need delegates as they can be used to write much more generic functions which are type safe also.
        It encapsulates the memory address of a function in the code. Events are created using delegates in .Net. When an event is published/thrown, the framework examines the delegate behind the event and then calls the function that is referred to by the delegate.

        Explain how to implement Delegates in C#.NET

        Here is an implementation of a very simple delegate that accepts no parameters.
        public delegate void MyDelegate();// Declaration
        class MyClass
        {
             public static void MyFunc()
             {
                 Console.WriteLine("MyFunc Called from a Delegate");
             }
             public static void Main()
             {
                    MyDelegate myDel = new MyDelegate(MyFunc);
                    myDel();
              }
        }
        namespace Delegates
        {
                 public delegate int DelegateToMethod(int x, int y);

                 public class Math
                 {
                        public static int Add(int a, int b)
                        {
                              return a + b;
                        }
                  public static int Multiply(int a, int b)
                  {
                       return a * b;
                  }
                  public static int Divide(int a, int b)
                  {
                         return a / b;
                  }
               }
               public class DelegateApp
               {
                    public static void Main()
                    {
                           DelegateToMethod aDelegate = new DelegateToMethod(Math.Add);
                           DelegateToMethod mDelegate = new DelegateToMethod(Math.Multiply);
                           DelegateToMethod mDelegate = new DelegateToMethod(Math.Multiply);
                           DelegateToMethod dDelegate = new DelegateToMethod(Math.Divide);
                           Console.WriteLine("Calling the method Math.Add() through the aDelegate object");
                           Console.WriteLine(aDelegate(5, 5));
                           Console.WriteLine("Calling the method Math.Multiply() through the mDelegate object");
                           Console.WriteLine(mDelegate(5, 5));
                           Console.WriteLine("Calling the method Math.Divide() through the dDelegate object");
                           Console.WriteLine(dDelegate(5, 5));
                           Console.ReadLine();
                    }
               }
        }

        CLR Triggers

        A CLR trigger could be a Date Definition or Date Manipulation Language trigger or could be an AFTER or INSTEAD OF trigger.
        Methods written in managed codes that are members of an assembly need to be executed provided the assembly is deployed in SQL 2005 using the CREATE assembly statement.
        The Microsoft.SqlServer.Server Namespace contains the required classes and enumerations for this objective.
        One can create a database object inside SQL Server that is developed in an assembly created in .Net CLR - it’s a special type of stored procedure that executes on an event. CLR triggers can reference data in the inserted and deleted tables, know about modified columns after an update statement, and access information about objects affected in the database as a result of DDL statements.

        Steps for creating CLR Trigger

        Follow these steps to create a CLR trigger of DML (after) type to perform an insert action:
        • Create a .NET class of triggering action
        • Make an assembly (.DLL) from that Class
        • Enable CLR environment in that database.
        • Register the assembly in SQL Server
        • Create CLR Trigger using that assembly
        Steps:
        • Define the trigger as a class and build the assembly
        • Register assembly in SQL Server using CREATE ASSEMBLY.
        • Create the trigger that reference the created assembly.