What’s new in ASP.NET 4.0
With Visual Studio 2010 Beta 1 and .NET Framework Beta 1 out for some time, this post is due from me for a long time. ASP.NET 4.0 has many improvements for different set of scenarios such as Webforms, Dynamic Data & AJAX based web development. There are also a lot of enhancements to the core runtime that powers ASP.NET such as Caching, Session & Request/Response objects.
For this post, we will examine some of the web form enhancements. There are sure a lot of them and we will examine some of them in the future posts.
Controlling View State using the ViewStateMode Property – Performance Enhancement
One of the most complained thing in ASP.NET Webform is the growing viewstate which becomes a concern for performance. While earlier you can set the EnableViewState property to true or false, post that, all the controls, by default inherit and even if you set it to enabled at control level, the behaviour was inconsistent.
With ASP.NET 4.0, the ViewStateMode property helps to determine for every control, whether the ViewState should be enabled, disabled or inherited accordingly. Ex.-
<asp:Panel ID="pnlViewState" runat="server" ViewStateMode="Disabled">
Disabled: <asp:Label ID="label1" runat="server" Text="Value set in markup" ViewStateMode="Inherit" /><br />
Enabled: <asp:Label ID="label2" runat="server" Text="Value set in markup" ViewStateMode="Enabled" />
<hr />
<asp:button ID="Button1" runat="server" Text="Postback" />
</asp:Panel>
In the code-behind
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
label1.Text = "Value set in code behind";
label2.Text = "Value set in code behind";
}
}
When you run the above page, you can find that the intial value for both the labels is set to “Value set in code behind” whereas after clicking on the button (postback), the value of label1 changes to “Value set in markup” whereas the value of label2 remains unchanged. As you can see, the Panel which holds both these lables has ViewStateMode set to Disabled and label1 is inherting the mode (this is the default if not specified) and label2 has it enabled. That is the reason label2 maintains viewstate while label1 loses it.
While it is arguably possible using the simple EnableViewState property earlier, it was never consistent. Considering the fact that in most of our performance sessions, we talk about disabling viewstate and then enabling it at control level while it doesnt work, this ViewStateMode is a welcome architectural change to improve performance.
Page Meta Keyword & Description – Search Engine Optimization feature
Upto Visual Studio 2008, one can set the Title of the page declaratively or through program using Page.Title. However, as more and more web traffic is happening through search engines, Page’s Title, Keyword and description become more important. Although the Keyword feature was exploited and hence many search engines today ignore it, Page Description is something still major search engines such as Google, Bing use for identifying and indexing pages based on content.
The new feature in ASP.NET 4.0 allows users to programmatically set the Page Description and Keywords as follows:-
protected void Page_Load(object sender, EventArgs e)
{
this.Page.Title = "My ASP.NET Blog";
this.Page.MetaKeywords = "ASP.NET, Web Development, Blog, ASP.NET Blog";
this.Page.MetaDescription = "This Blog contains posts related to ASP.NET and Web Development";
}
The above code appends the following markup
<meta name="keywords" content="ASP.NET, Web Development, Blog, ASP.NET Blog" />
<meta name="description" content="This Blog contains posts related to ASP.NET and Web Development" />
And the way it works is that, if the meta tags are already present in the HTML markup, whatever is set in the code behind will fill up the “content” part alone if the “name” tag is matching.
Although this looks simple, it is very useful in cases where you want to set these dynamically based on a condition / criteria. So far, these were set statically in the HTML. Now with Page Class level access, these can be set dynamically.
There are many more enhancements to Webforms such as Routing improvements, setting ClientID etc., which we will examine in the future posts.
Cheers !!!
Posted in: asp.net | Tags: asp.net asp.net 4.0 .net 4.0 meta keyword description seo eventargs webform clientidPHP versus ASP.NET – Windows versus Linux
How does IMPLEMENTATION Performance Compare ?
Usually, when someone creates benchmarks, they are trying to prove that their thing is faster than someone else's thing.
I’m PAID by Microsoft to write BOTH PHP and ASP.NET Code. I was doing PHP before .NET shipped. I love them both.
This makes it hard for me to say anything good about either one. When I confer a preference for something in PHP, my Microsoft peers send me flame mail and when I confer a preference for something in ASP.NET, my PHP friends come out of the woodwork to call me a Microsoft shill.
I started building and running these tests because everyone had opinions about comparative PHP performance (Windows versus Linux & 5.2 versus 5.3), but no one had any solid data.
So, I decided to collect some empirical evidence of my own.
Before you look at them, let m e provide some method details and context.
All tests were run on the SAME Machine.
A Toshiba Tecra M5 with 4 Gig of ram and a 60 Gig 7200 RPM Hard Drive.
Ubuntu 9 and Windows Server 2008 Standard were natively installed on 2 separate (but identical) hard drives.
The web servers were Apache2 on Linux and IIS 7 on Windows.
Both operating systems were fully patched / updated.
No Operating System or Development Runtime performance enhancements were added.
I wasn’t investigating how much speed an expert could custom tailor the tests to on a specific platform.
Yes, I could implement PHP Byte Caching, or for ASP.NET I could use Page Caching, Partial Page Caching, SQL Cache Dependency, Multi Threading, etc.
Both Windows and Linux Implementations of PHP will benefit from PHP Byte Code caching.
My goal was to determine the relative speed of THE IMPLEMENTATION.
I found the results both interesting and unexpected.
PHP on Linux Versus PHP on Windows…..
I really though one would just be faster than the other, but I was wrong. Some things are faster on Windows, other are faster on Linux.
- RAW statement execution seems faster on Windows.
- Function Calls were faster on Windows
- Object Creation / Access was faster on Linux with PHP 5.2 but faster on Windows with 5.3
- Library calls were faster on Linux. (Example: Encryption 3-5 times faster on Ubuntu.)
- File Access is faster on Linux by a small percentage, except for file copy operations which was as much as 60% slower on Windows probably due to the ACL advanced security.
- MySQL access with Linux is faster by more than a little and on Windows, MySQL access deteriorates in version 5.3 (This seems to be poor implementation, see PostgreSQL below.)
- PostgreSQL performance is very close on both platforms (within 6/100 of a second for 1000 Operations) – It’s faster on Windows and faster still on Windows with PHP 5.3
- MS SQL Server access from PHP 5.2 on Windows is marginally slower than MySQL access on Linux. (PHP 5.3 not yet supported at the time of this writing.)
So what does all that mean ?
- We can probably say that in terms of raw execution – performance on Linux versus Windows is probably a wash (more or less equivalent) so that the performance of PHP itself becomes a moot factor in choosing Linux or Windows for PHP application deployment.
- If you are building an application, or running an application that supports it, PostgreSQL might be a better database choice since it performs pretty much the same on Windows and Linux.
- If you are running an application that locks you in to Sun Microsystems’ MySQL and you want to run it on Windows, your should do scale planning. (My personal guess is that it’s unlikely that Sun will markedly improve MySQL performance on Windows. )
- Version 1 of the PHP Driver for SQL Server (V2 is in the works) is somewhat slower than MySQL or PostpreSQL but probably not enough to discourage use where diverse developer access is desired. (v2 ot the driver will improve performance. )
By and large I think the PHP team and the Microsoft IIS team have accomplished good raw performance equivalence across platforms. (Now we just need to get the Open Source Application teams (Drupal, WordPress, Joomle, etc.) to do performance optimization on both !)
PHP versus ASP.NET Raw Performance …..
By now you have cheated and looked at the spread sheet.
Yes, ASP.NET is universally faster than PHP (on Windows and on Linux) with the exceptions of File Copy and Attribute operations.
MySQL Access from PHP on Linux is a TINY bit faster than SQL Server access on Windows (assuming common data types and SELECT statements) but probably not enough to matter.
ASP.NET (C#) operations, object use, library calls, etc. are SIGNIFICANTLY faster that the PHP equivalents.
I know my PHP friends and the Linux dudes (and dude-etts) will probably come out of the wood work to refute my tests and results :)
I’ve always thought that if high end performance options were part of your needs requirements, then .NET programming has some advanced options “out of the box” like multi-threading, asynchronous requests, and a number of caching options.
NOTE – I’m not saying “ASP.NET is Faster so you shouldn't choose PHP !!!! I’ve always contended that the affable simplicity of PHP had some drawbacks for certain advanced applications. (Just as the early learning complexity of ASP.NET can have it’s drawbacks. )
To me (your mileage may vary) the exciting thing about PHP is not the language / platform so much as it is what thousands of clever PHP Developers have done with it (Drupal, Joomla, Wordpress, PHPBB, Nuke, etc.)
In any event, it’s nice to now have some data that PHP performance on Windows and Linux are “in the same ballpark”.
Now I can start writing those Windows specific PHP libraries I’ve been dreaming about for years !!
Posted in: General asp.net | Tags: asp.net php windows linux implementation performance compare windows versus linux sql server postgresql ms sql server mysqlCOMMENT WARNING
- I know some will be incensed by these tests. You are welcome to comment and disagree, but if you can't be polite I’ll simply delete your comments and block your IP address.
- If you dislike the results and want to refute them – DO THE WORK. Accompany your dissent with DATA. Take my code or write your own and argue with FACTS.
ASP.NET MVC V2 Preview 1 Released
The ASP.NET team just released the first public preview of ASP.NET MVC Version 2.
Today’s preview works with .NET 3.5 SP1 and VS 2008, and can be installed side-by-side on the same machine as ASP.NET MVC 1.0 (meaning they don’t conflict and your existing ASP.NET MVC 1.0 projects will not be impacted if you install it). If you have both ASP.NET MVC 1.0 and ASP.NET MVC 2.0 installed you’ll see two ASP.NET MVC project templates within Visual Studio 2008’s “New Project” dialog:
The release notes that come with the ASP.NET MVC 2 Preview release detail how to upgrade existing ASP.NET MVC 1.0 projects to use V2 if you’d like to migrate them forward to take advantage of the new features.
New Features
ASP.NET MVC V2 will include a bunch of new capabilities and features (some of these have already been called out on the ASP.NET MVC roadmap page). Today’s “Preview 1” release contains a first look at some of the new features. Many more features will show up in future preview builds. The Preview 1 bits are still relatively early - the team is releasing today’s build to start receiving and incorporating feedback.
Below are some quick details about some of the new Preview 1 capabilities:
Areas Support
ASP.NET MVC 2 includes support for a new feature called “areas” that allow you to more easily partition and group functionality across an MVC application.
Areas provide a means of grouping controllers and views to allow building subsections of a large application in relative isolation to other sections. Each area can be implemented as a separate ASP.NET MVC project which can then be referenced by the main application. This helps manage the complexity when building a large application and facilitates multiple teams working together on a single application together.
Below is a screen-shot that shows a single solution that has three projects. One of the projects is named “CompanySite” and includes the core site content, layout and controllers and views. There are then two separate “Area” projects - “Blogs” and “Forums”. These projects implement the functionality that exists under the /Blogs and /Forums URL sections of the site – and encapsulate all of the routing rules, controllers and views implementing these sections:
The Preview 1 release includes the first part of the areas feature implementation. It doesn’t include any tool support yet (right now you need to manually add a build task to create an area project and set it up). Future preview releases will include tooling support, and expand and refine the feature-set further.
DataAnnotation Validation Support
ASP.NET MVC 2 now includes built-in support for the DataAnnotation validation support that first shipped with .NET 3.5 SP1 – and which is used with ASP.NET Dynamic Data and .NET RIA Services. DataAnnotations provides an easy way to declaratively add validation rules to Model and ViewModel classes within an application, and have automatic binding and UI helper validation support within ASP.NET MVC.
To see this feature in action, we can create a new “Customer” ViewModel class like below that has five properties on it (implemented using the C# automatic property feature).
We can then decorate the properties with appropriate validation rules using the DataAnnotation attributes implemented within the System.ComponentModel.DataAnnotations namespace. The code below uses 4 different built-in validation rules – [Required], [StringLength], [Range], and [RegularExpression]. The namespace also includes a base class (ValidationAttribute) that you can subclass to create your own custom validation attributes.
We can then create a CustomersController class that has two Create action methods on it. The first Create action method handles HTTP GET requests to the “/Customers/Create” URL, and renders a view template based on an empty Customer object. The second Create action method handles HTTP POST requests to the same URL (and takes a Customer object as a method parameter). It checks if there are any model binding errors to the input submitted, and if there are errors it redisplays the view template using the already entered data. If there are no errors it displays a success view to the user:
Finally, we can right-click within either of the Create action methods above, choose the “Add View” context menu command, and automatically “scaffold” a “create” view template that is based on the Customer object. When we do this the generated scaffolded view template will contain the below HTML <form> for our Customer:
And now when we request the “/Customers/Create” URL in our browser we’ll get an initial empty form like below:
If we enter invalid input and perform a post to the server, the ASP.NET MVC 2 model binder will detect that there are DataAnnotations attributes on our Customer class, and automatically validate the posted form input using them. If there are errors our controller action method redisplays the form – which will cause the appropriate validation error messages to be rendered to the user like below. Note how the validation property error message strings we specified using the DataAnnotation attributes are displayed to the user by the Html.Validation helper methods. No extra code is required to enable this.

The above form will redisplay with error messages each time the user enters invalid input and attempts to perform a form post.
In a future ASP.NET MVC 2 preview we are planning to ship the jQuery Validation plugin as part of the default project template, and add support for the automatic client-side JavaScript enforcement of DataAnnotation validation rules as well. This will enable developers to easily add validation rules in one place on either a Model or ViewModel object, and have them be enforced both client and server-side everywhere it is used within the application.
If you do not wish to annotate your model or viewmodel classes directly, you can alternatively create a “buddy class” that accompanies your model class and encapsulates the DataAnnotaton rules separately. This capability is also useful for scenarios where VS is code-generating/updating the properties on a class directly and you cannot easily add attributes to the generated code (for example: classes generated by the LINQ to SQL or LINQ to Entities designers).
In addition to providing built-in support for DataAnnotations, the DefaultModelBinder class in ASP.NET MVC V2 now has new virtual methods that can be overridden to easily integrate other validation frameworks as well (for example: Castle Validator, EntLib Validation, etc). The validation UI helper methods in ASP.NET MVC are designed to support any type of validation framework (they have no direct knowledge of DataAnnotations).
Strongly Typed UI Helpers
ASP.NET MVC V2 includes new HTML UI helpers that enable you to use strong-typed lambda expressions when referencing the view template’s model object. This enables better compile-time checking of views (so that bugs can be found at build-time as opposed to runtime), and also enables better code intellisense support within view templates.
You can see an example of the better intellisense in action below – notice how I am getting a full listing of the customer model object’s properties when using the new Html.EditorFor() helper method:
Preview 1 has built-in support for new Html.EditorFor(), Html.LabelFor(), and Html.DisplayFor() helpers. An updated MVC futures assembly that we are shipping this week adds additional Html.TextBoxFor(), Html.TextAreaFor(), Html.DropDownListFor(), Html.HiddenFor(), and Html.ValidationMessageFor() helper methods as well (overtime these will move into the core ASP.NET MVC 2 assembly too).
Below you can see an updated version of the “create” view template for our customer creation scenario. Notice how instead of using string expressions to reference the customer object we are instead using strongly-typed lambda expressions with the UI helpers. We can get full intellisense and compile-time checking with all of them:
The Html.LabelFor() helper method above generates <label for="Name">Name:</label> HTML markup.
The Html.EditorFor() helper method can be used for any datatype value. By default it is smart and will output an appropriate HTML <input/> element based on the type to be edited. For example, it will generate <input type=”text”/> elements for the first four properties above (which are strings and integers). It will generate a <input type=”checkbox”/> element for the final “IsActive” property – which is of type boolean.
In addition to supporting simple data-types, the Html.EditorFor() helper method also allows you to pass more complex objects with multiple properties to it. By default it will loop over the public properties of the object and generate a <label>, <input/> element, and any appropriate validation message for each property it finds. For example, we could re-write the above view to have just a single Html.EditorFor() call for the Customer object to conceptually output the same markup as above:
The strongly typed helpers allow you to optionally decorate the properties of the Customer ViewModel class with [DisplayName] attributes to control the label string that is output for each property used (for example: instead of having a label text of “IsActive” we could apply a [DisplayName(“Is Active Customer:”)] attribute).
You can also add [ScaffoldColumn(false)] attributes to indicate that a particular property shouldn’t be rendered at all in scenarios like above where complex objects are passed to Html.EditorFor().
UI Helper Templating Support
The Html.EditorFor() and Html.DisplayFor() helper methods have built-in support for rendering both standard data-types as well as complex objects with multiple properties. As noted above, they also support basic customization of rendering by applying attributes like [DisplayName] and [ScaffoldColumn] to the ViewModel.
Often developers want to be able to customize the output from UI helpers even further, though, and have total control over what is generated. The Html.EditorFor() and Html.DisplayFor() helper methods support this via a templating mechanism that allows you to define external templates that can override and completely control the output rendered. Better yet, you can customize the content rendered on a per-datatype/class basis.
With Preview 1 you can now optionally add an “EditorTemplates” and/or “DisplayTemplates” folder underneath either a \Views\[controllername] directory (if you want to customize the rendering for views used by a specific controller) or underneath the \Views\Shared folder (if you want to customize the rendering for all views and controllers in an application).
You can then add partial template files to these folders to customize the output rendering performed on an individual datatype and/or class basis. For example, below I have added an EditorTemplates folder underneath the \Views\Shared folder – and added three custom template files to it:
The “Customer.ascx” template above indicates that I want to customize the output anytime Html.EditorFor() is passed a Customer object (for example: I could customize the exact ordering/layout of the Customer properties). The “DateTime.ascx” template above indicates that I want to customize the output anytime Html.EditorFor() is passed a DateTime property (for example: I might want to use a JavaScript datepicker instead of a plain textbox). I could optionally add an “Object.ascx” template to the folder if I wanted to override the default rendering of all objects.
In addition to customizing rendering on a per-type basis, you can also add “named templates” to the folder. A common scenario might be a “CountryDropDown” template that handles a string datatype – but instead of providing a standard textbox instead renders a <select> dropdownlist of country values that a user can pick from. Below is what this editor template might look like:
We can explicitly indicate that we want to use the above template by passing its name as an argument when we invoke the Html.EditorFor() helper method. For example, below in addition to specifying a lambda expression for our Country property, we are also specifying the name of the editor template to use when rendering it:
Alternatively, you can specify “UIHint” attributes on your ViewModel properties and types. This allows you to indicate the default editor or display template to use in a single place, and have it be used in all views across your application (without having to explicitly pass it as an argument to Html.EditorFor).
Below is an example of how to indicate using a UIHint attribute that the Customer.Country property (which is of type string) should by default use the CountryDropDown template when being rendered:
Once we set the above attribute on our ViewModel we no longer need to specify a template name explicitly when we use that property with Html.EditorFor(). And now when we hit refresh on our /Customers/Create URL our Country property will be rendered as a dropdown instead of a standard textbox:
Other Cool Features
ASP.NET MVC 2 Preview 1 includes a number of other small, but really nice, feature additions. A few of my favorites include:
New [HttpPost] Attribute
It is pretty common with ASP.NET MVC to split up the handling of a URL across two action methods – one that handles GET requests and one that handles POST requests.
With ASP.NET MVC 1 you used an [AcceptVerbs(HttpVerbs.Post)] attribute to indicate the “Post” version of an action method:
This still works with ASP.NET MVC 2. Alternatively, though, you can also now take advantage of a terser [HttpPost] attribute that does the same thing:
Default Parameter Values
Handling optional parameters is a pretty common web scenario. With ASP.NET MVC 1 you could handle optional parameters either by registering a custom routing rule and specifying a default value with it, or by marking an action method parameter as nullable and then adding code within your action method to handle whether it was null (and if so provide a default value).
ASP.NET MVC 2 Preview 1 now supports decorating action method parameters with the DefaultValueAttribute from the System.ComponentModel namespace. This allows you to specify a parameter value that ASP.NET MVC should pass in if it is not present as part of the request. For example, below is an example of how we could handle both the /Products/Browse/Beverages and /Products/Browse/Beverages?page=2 URLs – and have the “page” parameter value be “1” if it isn’t provided as part of the querystring:
VB today allows you to specify default parameter values directly within the VB language (avoiding the need to explicitly specify the DefaultValue attribute like above). C# in VS2010 will also support default values with optional parameters – which will enable you to rewrite the above code simply as:
This should make handling default/optional scenarios really easy and clean.
Binding Binary Data
ASP.NET MVC Preview 1 adds support for binding base64-encoded string values to properties of type byte[] and System.Data.Linq.Binary. There are now two overloaded versions of Html.Hidden() that can take these data-types. These can be useful for scenarios where you want to enable concurrency control within your application and want to roundtrip timestamp values of database rows within your forms.
Posted in: asp.net | Tags: asp.net asp.net mvc mvc mvc 2.0 v2 vs 2008 new project web application mvc web applicationPut Your Views (and Pages) On a Diet
One of the complaints I often hear with our default view engine and Pages is that there’s all this extra cruft in there with the whole page directive and stuff. But it turns out that you can get rid of a lot of it. Credit goes to David Ebbo, the oracle of all hidden gems within the inner workings of ASP.NET, for pointing me in the right direction on this.
First, let me show you what the before and after of our default Index view (reformatted to fit the format for this blog).
Before
<%@ Page Language="C#"
MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage" %>
<asp:Content ID="indexTitle"
ContentPlaceHolderID="TitleContent" runat="server">
Home Page
</asp:Content>
<asp:Content ID="indexContent"
ContentPlaceHolderID="MainContent" runat="server">
<h2><%= Html.Encode(ViewData["Message"]) %></h2>
<p>
To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc"
title="ASP.NET MVC Website">http://asp.net/mvc</a>.
</p>
</asp:Content>
After
<asp:Content ContentPlaceHolderID="TitleContent" runat="server">
Home Page
</asp:Content>
<asp:Content ContentPlaceHolderID="MainContent" runat="server">
<h2><%= Html.Encode(ViewData["Message"]) %></h2>
<p>
To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc"
title="ASP.NET MVC Website">http://asp.net/mvc</a>.
</p>
</asp:Content>
That ain’t your pappy’s Web Form view. I can see your reaction now:
Where’s the page declaration!? Where’s all the Content IDs!? Where’s the Master Page declaration!? Oh good, at least runat="server" is still there to anchor my sanity and comfort me at night.
It turns out that ASP.NET provides ways to set many of the defaults within Web.config. What I’ve done here (and which you can do in an ASP.NET MVC project or Web Forms project) is to set several of these defaults.
In the case of ASP.NET MVC, I opened up the Web.config file hiding away in the Views directory, not to be confused with the Web.config in your application root.
This Web.config is placed here because it is the default for all Views. I then made the following changes:
- Set the
compilationelement’sdefaultLanguageattribute to “C#”. - Set the
pageselement’smasterPageFileattribute to point to~/Views/Shared/Site.master. - Set the
pageselement’spageBaseTypeattribute toSystem.Web.Mvc.ViewPage(in this case, it was already set as part of the default ASP.NET MVC project template).
Below is what the web.config file looks like with my changes (I removed some details like other elements and attributes just to show the gist):
<configuration>
<system.web>
<compilation defaultLanguage="C#" />
<pages
masterPageFile="~/Views/Shared/Site.master"
pageBaseType="System.Web.Mvc.ViewPage"
userControlBaseType="System.Web.Mvc.ViewUserControl">
</pages>
</system.web>
</configuration>
With this in place, as long as my views don’t deviate from these settings, I won’t have to declare the Page directive.
Of course, if you’re using strongly typed views, you’ll need the Page directive to specify the ViewPage type, but that’s it.
Also, don’t forget that you can get rid of all them ugly Register declarations by registering custom controls in Web.config.
You can also get rid of those ugly Import directives by importing namespaces in Web.config.
<configuration>
<system.web>
<pages>
<namespaces>
<add namespace="Haack.Mvc.Helpers" />
</namespaces>
</pages>
</system.web>
</configuration>
By following these techniques, you can get rid of a lot of cruft within your pages and views and keep them slimmer and fitter. Of course, what I’ve shown here is merely putting your views on a syntax diet. The more important diet for your views is to keep the amount of code minimal and restricted to presentation concerns, but that’s a post for another day as Rob has already covered it.
Sadly, there is no getting rid of runat="server" yet short of switching another view engine. But at this point, I like to think of him as that obnoxious friend from high school your wife hates but you still keep around to remind you of your roots. ;)
Hope you enjoy these tips and use them to put your views on a diet. After all, isn’t it the view’s job to look good for the beach?
Posted in: asp.net | Tags: asp.net mvc content index view reformatted format38 Interview Questions and Answers of ASP.NET
1. Describe the role of inetinfo.exe, aspnet_isapi.dll and aspnet_wp.exe in the page loading process.
inetinfo.exe is theMicrosoft IIS server running, handling ASP.NET requests among other things.When an ASP.NET request is received (usually a file with .aspx extension),the ISAPI filter aspnet_isapi.dll takes care of it by passing the request 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 eventhandlers, allowing the main DataGrid event handler to take care of its constituents.
8. Suppose you want a certain ASP.NET function executed on MouseOver overa 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 connection to the original data source.
· Data in a DataSet is bulk-loaded, rather than being loaded on demand.
· There's no concept of cursor types in a DataSet.
· DataSets have no current record pointer You can use For Each loops to move through the data.
· You can store many edits in a DataSet, and write them to the original data source in a single operation.
· Though the DataSet is universal, other objects in ADO.NET come in different versions for different data sources.
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. 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
36. Which control would you use if you needed to make sure the values in two different controls matched?
CompareValidator Control
37. 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.
38. How many classes can a single .NET DLL contain?
It can contain many classes.
Series 2
- Explain the .NET architecture.
- How many languages .NET is supporting now?
- When .NET was introduced it came with several languages. VB.NET, C#, COBOL and Perl, etc. The site DotNetLanguages.Net says 44 languages are supported. - How is .NET able to support multiple languages?
- a language should comply with the Common Language Runtime standard to become a .NET language. In .NET, code is compiled to Microsoft Intermediate Language (MSIL for short). This is called as Managed Code. This Managed code is run in .NET environment. So after compilation to this IL the language is not a barrier. A code can call or use a function written in another language. - How ASP .NET different from ASP?
- Scripting is separated from the HTML, Code is compiled as a DLL, these DLLs can be executed on the server. - Resource Files: How to use the resource files, how to know which language to use?
- What is smart navigation?
- The cursor position is maintained when the page gets refreshed due to the server side validation and the page gets refreshed. - What is view state?
- The web is stateless. But in ASP.NET, the state of a page is maintained in the in the page itself automatically. How? The values are encrypted and saved in hidden controls. this is done automatically by the ASP.NET. This can be switched off / on for a single control - Explain the life cycle of an ASP .NET page.
- How do you validate the controls in an ASP .NET page?
- Using special validation controls that are meant for this. We have Range Validator, Email Validator. - Can the validation be done in the server side? Or this can be done only in the Client side?
- Client side is done by default. Server side validation is also possible. We can switch off the client side and server side can be done. - How to manage pagination in a page?
- Using pagination option in DataGrid control. We have to set the number of records for a page, then it takes care of pagination by itself. - What is ADO .NET and what is difference between ADO and ADO.NET?
- ADO.NET is stateless mechanism. I can treat the ADO.Net as a separate in-memory database where in I can use relationships between the tables and select insert and updates to the database. I can update the actual database as a batch.