Friday 20 June 2014

ASP.NET



1 . What is ASP.NET?

ASP.NET is a programming framework built on the common language runtime that can be used on a server to build powerful Web applications
.
2 . Why does my ASP.NET file have multiple tag with runat=server?

This means that ASP.Net is not properly registered with IIS.
.Net framework provides an Administration utility that manages the installation and uninstallation of multiple versions of ASP.NET on a single machine. You can find the file in C:\WINNT\Microsoft.NET\Framework\v**\aspnet_regiis.exe

use the command: aspnet_regiis.exe -u ---> to uninstall current asp.net version.
use the command: aspnet_regiis.exe -i ---> to install current asp.net version.


For Windows Server 2003, you must use aspnet_regiis -i -enable
This is because of the "Web Service Extensions" feature in IIS 6

(if you install VS.NET or the framework without IIS installed, and then go back in and install IIS afterwards, you have to re-register so that ASP.NET 'hooks' into IIS properly."
3 . How to find out what version of ASP.NET I am using on my machine?

VB.NET

Response.Write(System.Environment.Version.ToString() )


C#

Response.Write(System.Environment.Version.ToString() );
4 . Is it possible to pass a querystring from an .asp page to aspx page?

Yes you can pass querystring from .asp to ASP.NET page .asp

<%response.redirect "webform1.aspx?id=11"%>


.aspx
VB.NET

Response.Write (Request("id").ToString ())


C#

Response.Write (Request["id"].ToString ());
5 . How to comment out ASP.NET Tags?

<%--<asp:Label id="Label1" style="Z-INDEX: 101; LEFT: 8px; POSITION: absolute; TOP: 48px" runat="server">Label</asp:Label>--%>
6 . What is a ViewState?

In classic ASP, when a form is submitted the form values are cleared. In some cases the form is submitted with huge information. In such cases if the server comes back with error, one has to re-enter correct information in the form. But submitting clears up all form values. This happens as the site does not maintain any state (ViewState).

In ASP .NET, when the form is submitted the form reappears in the browser with all form values. This is because ASP .NET maintains your ViewState. ViewState is a state management technique built in ASP.NET. Its purpose is to keep the state of controls during subsequent postbacks by the same user. The ViewState indicates the status of the page when submitted to the server. The status is defined through a hidden field placed on each page with a <form runat="server"> control.

<input type="hidden" name= "__VIEWSTATE"value="dDwyNTA3OTU0NDM7Oz7t5TntzkOUeB0QVV6FT2hvQwtpPw==" />


If you want to NOT maintain the ViewState, include the directive <%@ Page EnableViewState="false"%> at the top of an .aspx page If you do not want to maintain Viewstate for any control add the attribute EnableViewState="false" to any control. For more details refer The ASP.NET View State
7 . Where can I get the details on Migration of existing projects using various technologies to ASP.NET?

Microsoft has designed Migration Assistants to help us convert existing pages and applications to ASP.NET. It does not make the conversion process completely automatic, but it will speed up project by automating some of the steps required for migration.
Below are the Code Migration Assistants

    * ASP to ASP.NET Migration Assistant
    * PHP to ASP.NET Migration Assistant
    * JSP to ASP.NET Migration Assistant

Refer Migrating to ASP.Net
8 . What is the equivalent of date() and time() in ASP.NET?

VB.NET

System.DateTime.Now.ToShortDateString()
System.DateTime.Now.ToShortTimeString()


C#

System.DateTime.Now.ToShortDateString();
System.DateTime.Now.ToShortTimeString();
9 . How to prevent a button from validating it's form?

Set the CauseValidation property of the button control to False
10 . How to get the IP address of the host accessing my site?

VB.NET

Response.Write (Request.UserHostAddress.ToString ())


C#

Response.Write (Request.UserHostAddress.ToString ());

> 
11 . How to access the Parameters passed in via the URL?

Call the Request.QueryStringmethod passing in the key. The method will return the parameter value associated with that key. VB.NET

Request.QueryString("id")


C#

Request.QueryString["id"];
12 . How to display a Wait page while a query is running?

Refer Asynchronous Wait State Pattern in ASP.NET
13 . How to implement Form based Authentication in ASP.NET application?

For

    * VB.NET
    * C#

14 . How to catch the 404 error in my web application and provide more useful information?

In the global.asax Application_error Event write the following code

VB.NET

Dim ex As Exception = Server.GetLastError().GetBaseException()
If TypeOf ex Is System.IO.FileNotFoundException Then
     'your code
     'Response.Redirect("err404.aspx")
Else
     'your code
End If


C#

Exception ex = Server.GetLastError().GetBaseException();
if (ex.GetType() == typeof(System.IO.FileNotFoundException))
{
     //your code
     Response.Redirect ("err404.aspx");
}
else
{
     //your code
}
15 . Is there a method similar to Response.Redirect that will send variables to the destination page other than using a query string or the post method?

Server.Transfer preserves the current page context, so that in the target page you can extract values and such. However, it can have side effects; because Server.Transfer doesnt' go through the browser, the browser doesn't update its history and if the user clicks Back, they go to the page previous to the source page.

Another way to pass values is to use something like a LinkButton. It posts back to the source page, where you can get the values you need, put them in Session, and then use Response.Redirect to transfer to the target page. (This does bounce off the browser.) In the target page you can read the Session values as required.

Refer to Passing Values Between Web Forms Pages for more information.
16 . What are the differences between HTML versus Server Control?

Refer

    * ASP.NET Server Controls Recommendations
    * Introduction to ASP.NET Server Controls

17 . How can I change the action of a form through code?

You can't change it. The action attribute is owned by ASP.NET. Handle Events and Transfer.

For work around refer to Paul Wilson's Multiple Forms and Non-PostBack Forms - Solution
18 . Is there any control that allows user to select a time from a clock - in other words is there a clock control?

Peter Blum has developed some controls. Check out Peter's Date Package: TimeOfDayTextBox and DurationTextBox Controls
19 . How to Compare time?

VB.NET

Dim t1 As String = DateTime.Parse("3:30 PM").ToString("t")
Dim t2 As String = DateTime.Now.ToString("t")
If DateTime.Compare(DateTime.Parse(t1), DateTime.Parse(t2)) < 0 Then
     Response.Write(t1.ToString() & " is < than " & t2.ToString())
Else
     Response.Write(t1.ToString() & " is > than " & t2.ToString())
End If


C#

string t1 = DateTime.Parse("3:30 PM").ToString("t");
string t2 = DateTime.Now.ToString("t");
if (DateTime.Compare(DateTime.Parse (t1), DateTime.Parse (t2)) < 0 )
{
     Response.Write(t1.ToString() + " is < than " + t2.ToString());
}
else
{
     Response.Write(t1.ToString() + " is > than " + t2.ToString());
}

20 . How To work with TimeSpan Class?

VB.NET

Dim adate As DateTime = DateTime.Parse("06/24/2003")
Dim bdate As DateTime = DateTime.Parse("06/28/2003")
Dim ts As New TimeSpan(bdate.Ticks - adate.Ticks)
Response.Write(ts.TotalDays & "<br>")
Response.Write(ts.TotalHours & ":" & ts.TotalMinutes & ":" & ts.TotalSeconds & ":" & ts.TotalMilliseconds)


C#

DateTime adate = DateTime.Parse("06/24/2003");
DateTime bdate = DateTime.Parse("06/28/2003");
TimeSpan ts = new TimeSpan (bdate.Ticks - adate.Ticks);
Response.Write(ts.TotalDays.ToString () + "<br>");
Response.Write(ts.TotalHours.ToString() + ":" + ts.TotalMinutes.ToString() + ":" + ts.TotalSeconds.ToString() + ":" + ts.TotalMilliseconds.ToString() );
21 . Where can I get information on Cookies in ASP.NET?

Refer Mike Pope's article Basics of Cookies in ASP.NET
22 . Does ASP.Net still recognize the global.asa file?

ASP.Net does not recognize the standard ASP global.asa file. Instead it uses a file named global.asax with the same - plus additional - functionality.
23 . How should I destroy my objects in ASP.Net?

ASP.Net actually has very solid internal garbage collection. So this is not an issue as it was in previous versions of Active Server Pages.
Link to more information: <gcConcurrent> Element
24 . Are there resources online with tips on ASP to ASP.Net conversions?

Microsoft has deisnged The ASP to ASP.NET Migration Assistant help us convert ASP pages and applications to ASP.NET. It does not make the conversion process completely automatic, but it will speed up project by automating some of the steps required for migration.

The following Code Migration Assistants are discussed in the link below.

    * ASP to ASP.NET Migration Assistant
    * PHP to ASP.NET Migration Assistant
    * JSP to ASP.NET Migration Assistant

Refer Migrating to ASP.Net

Also refer:

    * Microsoft's ASP to ASP.NET Code Migration Assistant
    * John Peterson's article Microsoft's ASP to ASP.NET Migration Assistant
    * Paolo Cavone's article From ASP to ASP.NET... Painlessly!

25 . How do I publish my ASP.NET application to my ISP's web server?

Your ISP must first create an IIS application and apply the Front Page Server Extensions to it. Then in Visual Studio .NET, select the "Project | Copy Project" menu. Then enter the URL and select the FrontPage web access method. The "Copy Project" feature copies all of the necessary files to your ISP's machine for your ASP.NET application to run.

You can also FTP your files to your ISP web server. But you must know which files to upload. For more details refer PRB: Remote ASP.NET Projects Require IIS on the Client Computer or FrontPage Server Extensions on the Server Computer
26 . Why do i get error message "Could not load type" whenever I browse to my ASP.NET web site?

Your code-behind files for either your .aspx or the global.aspx page have not been complied. Use Visual Studio .NET's "Build | Build Solution" menu, or run the command line compiler.

For more details refer PRB: "Could not load type" error message when you browse to .aspx page
27 . Will the WebMatrix SqlDataSourceControl work with a MySQL connection?

SqlDataSourceControl lets you connect and work with MS SQL DB, while AccessDataSourceControl do the same thing but for MS Access DB. Therefore SqlDataSourceControl can't help you in your MySql connectivity .
For Connectivity with MySql refer Accessing MySQL Database with ASP.NET
28 . Can I combine classic ASP and ASP.NET pages?

No.
ASP pages can run in the same site as ASP.NET pages, but you can't mix in a page. Also ASP and ASP.NET won't share their session.
29 . What is the difference between src and Code-Behind?

Src attribute means you deploy the source code files and everything is compiled JIT (just-in-time) as needed. Many people prefer this since they don't have to manually worry about compiling and messing with dlls -- it just works. Of course, the source is now on the server, for anyone with access to the server -- but not just anyone on the web.

CodeBehind attribute doesn't really "do" anything, its just a helper for VS.NET to associate the code file with the aspx file. This is necessary since VS.NET automates the pre-compiling that is harder by hand, and therefore the Src attribute is also gone. Now there is only a dll to deploy, no source, so it is certainly better protected, although its always decompilable even then.
30 . How can I get the value of input box with type hidden in code-behind?

You can set the runat= server for the hidden control and you can use ControlName.Value to get its value in CodeBehind file

> 
31 . I have created a .NET user control page (.ascx) but I cannot compile and run it.

User control (ascx) can't be run on it own, but you can drag it onto any web page (aspx) and then run it.
32 . What is a .resx file?

The .resx resource file format consists of XML entries, which specify objects and strings inside XML tags. This is useful for localization. For more details refer Resources in .resx files
33 . Is it possible to use a style sheet class directly on a control instead of using inline or page-level formatting ?

Every WebControl derived control has a CssClass property which allows you to set it's format to a style sheet.
34 . Can I recieve both HTML markup for page and code in the ASP.NET web page's source code portion in the Web browser?

No. The Web browser recieves only HTML markup.
No source code or web control syntax is passed back to the web browser.
35 . Why can't I put <%@ Page Language="C " %> where at the top of an ASPX file and write my server-side scripts in C ?

The parsers ASP.NET uses to extract code from ASPX files understand C#, Visual Basic.NET, and JScript.NET. You can write server-side scripts in any language supported by a .NET compiler.
36 . ASP pages that worked pefectly on Windows 2000 Server and IIS 5.0 do not work on Windows 2003 Server with IIS 6.0. ASP.NET pages work fine. Why?

Start -> Settings -> Control Panel -> Administrative Tools -> and double clicking IIS Manager.
Go to the Web Service Extensions tab, click Active Server Pages, then press the "Allow" button on the left
37 . Why do I get error message "Error creating assembly manifest: Error reading key file 'key.snk' -- The system cannot find the file specified"?

Check the location of the key.snk file relative to the assembly file. Provide an explicit path or a relative path.

<Assembly: AssemblyKeyFileAttribute("Drive:\key.snk")>
38 . How to get URL without querystring?

VB.NET

Dim stringUri As String = "http://www.syncfusion.com/?id=1&auid=16"
Dim weburi As Uri = New Uri(stringUri)
Dim query As String = weburi.Query
Dim weburl As String = stringUri.Substring(0, stringUri.Length - query.Length)
Response.Write(weburl)


C#

string stringUri = "http://www.syncfusion.com/?id=1&auid=16";
Uri weburi = new Uri(stringUri);
string query = weburi.Query;
string weburl = stringUri.Substring(0, stringUri.Length - query.Length);
Response.Write (weburl);
39 . What is the best way to output only time and not Date?

Use DateTime as follows VB.NET

Response.Write(DateTime.Now.ToString("hh:mm:ss"))


C#

Response.Write(DateTime.Now.ToString("hh:mm:ss"));
40 . Do I have to compile code if I am changing the content of my aspx.cs file?

Yes if you have used Codebehind="my.aspx.cs".
Not if you used src="my.aspx.cs" in your page declaration.

> 
41 . How to grab the referring URL?

VB.NET

Response.Write ( Request.UrlReferrer.ToString())


C#

Response.Write ( Request.UrlReferrer.ToString());
42 . My ASP code gives an error "Compiler Error Message: BC30289: Statement cannot appear within a method body. End of method assumed" when changed to .aspx?

Use a <script runat=server> block instead of the <% %> syntax to define Subs.
Make sure you have proper events associated with the code and have start and end of procedure or function wirtten properly.
43 . How can I save images ?

You need a stream to read the response, WebResponse.GetResponseStream(), and a stream to write it to the hard drive. FileStream should do the trick. You'll have to write to the filestream what you read from the response stream.
44 . How can I logout when using FormsAuthentication?

FormsAuthentication.SignOut()
45 . Why do I get a blank page when I use Server.Transfer("page1.htm") to transfer to a different page?

Server.Transfer only works with .aspx pages
You can't use Transfer method with HTML pages
46 . How to detect the User's culture?

VB.NET

Dim sLang As String
sLang = Request.UserLanguages(0)
Response.Write(sLang)


C#

string sLang ;
sLang = Request.UserLanguages[0];
Response.Write (sLang);
47 . What is the difference between CurrentCulture property and the CurrentUICulture property?
# CurrentCulture property : affects how the .NET Framework handles dates, currencies, sorting and formatting issues
# CurrentUICulture property : determines which satellite assembly is used when loading resources
48 . Can I read the hard disk serial # of the client computer using ASP.NET?

No. Such information is not passed to the server with a http request.
49 . What is xxx(src As Object, e As EventArgs)?

xxx is an event handler
src is the object that fires the event
e is an event argument object that contains more information about the event
An event handler is used when one object wants to be notified when an event happens in another object
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,

       
Dot Net - C#.Net””””””””””””””””””””
1 . Does C# support multiple-inheritance?

No.
2 . Who is a protected class-level variable available to?

It is available to any sub-class (a class inheriting this class).
3 . 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.
4 . Describe the accessibility modifier “protected internal”.

It is available to classes that are within the same assembly and derived from the specified base class.
5 . What’s the top .NET class that everything is derived from?

System.Object.
6 . 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.
7 . 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.
8 . 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.
9 . Can you store multiple data types in System.Array?

No.
10 . 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.
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

       
Dot Net - Asp.Net 2.0 Interview Questions
1 . What are the new Data Controls in Asp.net 2.0?

Data access in ASP.NET 2.0 can be accomplished completely declaratively (no code) using the new data-bound and data source controls. There are new data source controls to represent different data backends such as SQL database, business objects, and XML, and there are new data-bound controls for rendering common UI for data, such as gridview, detailsview, and formview.


2 . What are the new Navigation Controls in Asp.net 2.0?

The navigation controls provide common UI for navigating between pages in your site, such as treeview, menu, and sitemappath. These controls use the site navigation service in ASP.NET 2.0 to retrieve the custom structure you have defined for your site.
3 . What are the new Login Controlsin Asp.net 2.0?

The new login controls provide the building blocks to add authentication and authorization-based UI to your site, such as login forms, create user forms, password retrieval, and custom UI for logged in users or roles. These controls use the built-in membership and role services in ASP.NET 2.0 to interact with the user and role information defined for your site.
4 . What are the new Web Part Controls in Asp.net 2.0 ?

Web parts are an exciting new family of controls that enable you to add rich, personalized content and layout to your site, as well as the ability to edit that content and layout directly from your application pages. These controls rely on the personalization services in ASP.NET 2.0 to provide a unique experience for each user in your application.
5 . What are Master Pages?

This feature provides the ability to define common structure and interface elements for your site, such as a page header, footer, or navigation bar, in a common location called a "master page", to be shared by many pages in your site. In one simple place you can control the look, feel, and much of functionality for an entire Web site. This improves the maintainability of your site and avoids unnecessary duplication of code for shared site structure or behavior.
6 . What are Themes and Skins in 2.0, explain usgae scenario?

The themes and skins features in ASP.NET 2.0 allow for easy customization of your site's look-and-feel. You can define style information in a common location called a "theme", and apply that style information globally to pages or controls in your site. Like Master Pages, this improves the maintainability of your site and avoid unnecessary duplication of code for shared styles.
7 . What is a profile object, why is it used?

Using the new personalization services in ASP.NET 2.0 you can easily create customized experiences within Web applications. The Profile object enables developers to easily build strongly-typed, sticky data stores for user accounts and build highly customized, relationship based experiences. At the same time, a developer can leverage Web Parts and the personalization service to enable Web site visitors to completely control the layout and behavior of the site, with the knowledge that the site is completely customized for them. Personalizaton scenarios are now easier to build than ever before and require significantly less code and effort to implement.
8 . What is Configuration API?

ASP.NET 2.0 contains new configuration management APIs, enabling users to programmatically build programs or scripts that create, read, and update Web.config and machine.config configuration files.
9 . What is MMC Admin Tool?

ASP.NET 2.0 provides a new comprehensive admin tool that plugs into the existing IIS Administration MMC, enabling an administrator to graphically read or change common settings within our XML configuration files.
10 . Explain the use of Pre-compilation Tool?

ASP.NET 2.0 delivers a new application deployment utility that enables both developers and administrators to precompile a dynamic ASP.NET application prior to deployment. This precompilation automatically identifies any compilation issues anywhere within the site, as well as enables ASP.NET applications to be deployed without any source being stored on the server (one can optionally remove the content of .aspx files as part of the compile phase), further protecting your intellectual property.
11 . How is application management and maintenance improved in Asp.net 2.0?

ASP.NET 2.0 also provides new health-monitoring support to enable administrators to be automatically notified when an application on a server starts to experience problems. New tracing features will enable administrators to capture run-time and request data from a production server to better diagnose issues. ASP.NET 2.0 is delivering features that will enable developers and administrators to simplify the day-to-day management and maintenance of their Web applications.
12 . What are Provider-driven Application Services? explain in detail?
ASP.NET 2.0 now includes built-in support for membership (user name/password credential storage) and role management services out of the box. The new personalization service enables quick storage/retrieval of user settings and preferences, facilitating rich customization with minimal code. The new site navigation system enables developers to quickly build link structures consistently across a site. As all of these services are provider-driven, they can be easily swapped out and replaced with your own custom implementation. With this extensibility option, you have complete control over the data store and schema that drives these rich application services.
13 . Explain Server Control Extensibility with reference to Asp.net 2.0 ?
ASP.NET 2.0 includes improved support for control extensibility, such as more base classes that encapsulate common behaviors, improved designer support, more APIs for interacting with client-side script, metadata-driven support for new features like themes and accessibility verification, better state management, and more.
14 . What are the Data Source Controls?
Data access in ASP.NET 2.0 is now performed declaratively using data source controls on a page. In this model, support for new data backend storage providers can be easily added by implementing custom data source controls. Additionally, the SqlDataSource control that ships in the box has built-in support for any ADO.NET managed provider that implements the new provider factory model in ADO.NET.
15 . What are Compilation Build Providers?
Dynamic compilation in ASP.NET 2.0 is now handled by extensible compilation build providers, which associate a particular file extension with a handler that knows how to compile that extension dynamically at runtime. For example, .resx files can be dynamically compiled to resources, .wsdl files to web service proxies, and .xsd files to typed DataSet objects. In addition to the built-in support, it is easy to add support for additional extensions by implementing a custom build provider and registering it in Web.config.

16 . What is Expression Builders, why would you use it?

ASP.NET 2.0 introduces a declarative new syntax for referencing code to substitute values into the page, called Expression Builders. ASP.NET 2.0 includes expression builders for referencing string resources for localization, connection strings, application settings, and profile values. You can also write your own expression builders to create your own custom syntax to substitute values in a page rendering.

17 . Is ASP.NET 64-Bit enabled? how?

ASP.NET 2.0 is now 64-bit enabled, meaning it can take advantage of the full memory address space of new 64-bit processors and servers. Developers can simply copy existing 32-bit ASP.NET applications onto a 64-bit ASP.NET 2.0 server and have them automatically be JIT compiled and executed as native 64-bit applications (no source code changes or manual re-compile are required).
18 . Explain how Caching in Asp.net 2.0 is different from Caching in Asp.net 1.1?
ASP.NET 2.0 also now includes automatic database server cache invalidation. This powerful and easy-to-use feature allows developers to aggressively output cache database-driven page and partial page content within a site and have ASP.NET automatically invalidate these cache entries and refresh the content whenever the back-end database changes. Developers can now safely cache time-critical content for long periods without worrying about serving visitors stale data.
19 . Can we bind data to a server control without writing code in .NET?
Yes, that is possible. ASP.NET 2.0 has the feature of declarative solution for data binding which requires no code at all for the most common data scenarios, such as:
* Selecting and displaying
* Data Sorting
* Paging and Caching
* Data Updating
* Inserting and Deleting Data


20 . How to use Masterpages and Contentpages in ASP.NET 2.0? What is a Masterpage? What is a ContentPage? How to setup master-content pages in ASP.NET 2.0?
A Master Page is the mother of the page and the content page is the baby! There may be many babies of the mother. A master page may have plenty of content pages within it. There also may be a master page within a master page, which is called a nested master page.
So whats a master page in ASP.NET 2.0? A Master Page is a page that contains markup and controls that are shared across multiple pages in your site. For example, if required that all pages should have the same header and footer banners or the common navigation menu, the Master page can be written once, and all the content pages can access the common master page. The content pages inherit the tags inside the master page.

Next question is how to define a master page. The answer is...

To define a Master Page, it may be written like a normal page. Master Pages can contain markup, controls, or code, or any combination of these tags. The Content pages are rendered in a master page control called as ContentPlaceHolder control. A ContentPlaceHolder defines a region of the master page rendering that can be exchanged with content from a page associated to the master. A ContentPlaceHolder can also contain default content, when in case the derive page does not need to override this content. Below is the markup of how to use a Contentplaceholder.

<asp:contentplaceholder id="ContentPlaceHolderInterviewQuestions" runat="server"/>

<asp:contentplaceholder id="ContentPlaceHolderInterviewQuestions" runat="server">
<h3>Welcome to the .NET Interview Questions website!</h3>
</asp:contentplaceholder>

A master page has the extension .master, unlike a normal web form that has the extenstion .aspx. A page may derive from a Master Page by defining a MasterPageFile attribute on its Page directive. Below is the markup of a content page.

<%@ Page MasterPageFile="Masterpage.master" %>
<asp:content id="Content1" contentplaceholderid="ContentPlaceHolderInterviewQuestions" runat="server">
Here goes contents of ContentPlaceHolderInterviewQuestions </asp:content>
</asp:content>

So how does Content page access a master page? It is also possible for a Content Page to programmatically access a Master Page. A ContentPage may create a strongly-typed reference to the Master Page using the <%@ MasterType %> directive, which specifies the virtual path to the masterpage as below...

<%@ MasterType VirtualPath="Masterpage.master" %>

The Content Page may then reference the Master Page using the Master property of the Page class:

Master.FooterText = "Some text on the footer of .NET Interview Questions page";
Label lb1 = Master.FindControl("label2");

As with the example above, FooterText is a public property exposed on the Master Page, whereas label2 is a server side control on the Master Page.

Note that the FindControl method is a very useful and a very important method, that may be used for finding a control in a content page from a master page and vice versa.
21 . What is a nested Masterpage in ASP.NET 2.0? Can there be a master page inside a masterpage?

When a master page is placed inside the contentplaceholder of a masterpage, then the masterpage is said to be nested. In other words, there is one parent masterpage, and the child masterpage is inside the contentplaceholder of the parent masterpage.
22 . What is a SiteMapPath control in ASP.NET 2.0?

An asp:SiteMapPath control is a Navigation Control that comes along with the ASP.NET 2.0 framework. The sitemappath control consists site link's data in XML format. The emergence of the Sitemappath control in ASP.NET 2.0 has totally eliminated the clumsy code used in bread crumbs by veteran web developers in Classic ASP and ASP.NET 1.1. These bread crumbs were comparatively tougher to maintain.

Now say you need to maintain a Sitemap of a Site having the following links...

Home Products     Medicines     Soaps     Alcohol Support     Phone Support     Email Support Contact Us

Instead of hard coding these links inside your code, all this information may be maintained in an XML based Web.sitemap file which can be bind to an asp:SiteMapPath control, and this would display like a website breadcrumb. Easier than before!

The SiteMapPath control's SiteMapProvider property is used to set the site's sitemap provider. This sitemap provider is another control called asp:XmlDataSource control. This needs to be registered in the web.config file. If the SiteMapProvider property is not specified, then the default SiteMap Provider information is picked up from the web.config file.

Note:The other two navigation controls in ASP.NET 2 are the Menu control and the TreeView control.

The XmlDataSource control loads an XML file that is specified using the DataFile property. This control inherits from the HierarchicalDataSourceControl class.

Example XML below:
<asp:SiteMapPath ID="smm1" runat="server" SiteMapProvider="xds1"></asp:SiteMapPath>
<asp:XmlDataSource ID="xds1" DataFile="somefile.xml" runat="server"></asp:XmlDataSource>


If DataFile is not used in the XmlDataSource, the siteMapFile property can be set in the web.config.
In order to specify XML Data Source in web.config, see below:

<configuration>
<system.web>

<siteMap defaultProvider="XmlSiteMapProvider" enabled="true">
 <providers>
 <clear/>
 <add name="XmlSiteMapProvider"
 <description="Default SiteMap provider"
 <type="System.Web.XmlSiteMapProvider"
 <siteMapFile="~/Web.sitemap"
 </>
 </providers>
</siteMap>
</system.web>
</configuration>
23 . How to sort the contents of a GridView control?

The ASP.NET 2.0 GridView control is a powerful control, the enables sorting of the rows based on a column, all this possible, without writing code. Well thats what we call power!

The GridView control relies on the underlying data source control to whom this is bound for the sorting capability. The GridView needs to have an AccessDataSource or an SQlDataSource or an ObjectDataSource (if the SortParameterName property is set to a value allowed.

The AllowSorting property of the GridView control, when set to true, enables sorting of the GridView. A sortable GridView has the Header column represented as a LinkButton control. When this Link Button is clicked, the Sorting event of the GridView is raised server-side, which causes a postback and in turn, sorts the GridView control's records.
24 . What does the Hotspot class in .NET do? What is an ImageMap in ASP.NET?

An ImageMap is an ASP.NET control that allows clicks inside a polygon like (called Hotspot) region in a webpage. Well, that actually means you may create a star-shaped or diamond shaped button.

There are several pre-defined shapes allowed inside an ImageMap for which templates may be used. For example, for a rectangle, an asp:RectangularHotSpot may be used. For a circle, an asp:CircleHotSpot may be used. And for creating stars & diamonds, an asp:PolygonHotSpot may be used. An image may also be put in an ImageMap which may be specified by its ImageUrl property.

In order to invoke an event, the HotSpotMode property needs to be set to PostBack. Further, if several HotSpots are placed inside an ImageMap, the event of the ImageMap may be passed a value using the PostBackValue property.

Code below shows how to create a Polygon HotSpot using an ImageMap.

<asp:ImageMap ID="ImageMap1" Runat="Server"
ImageUrl="Photo.gif" OnClick="SomeEvent"
AlternateText="Click Here"
HotSpotMode="Navigate">

<asp:PolygonHotSpot
AlternateText="Click Here Too!"
Coordinates="100,150, 250,350, 210,290, 90,350, 60,240"
NavigateUrl="http://www.asp.net"
Target="_blank"/>
</asp:ImageMap>
25 . How do we update and delete data in a gridview? Datakeynames property in .NET?

The best way to Update or Delete a record in a GridView control is to include a CheckBox column and a Submit Button.

The GridView has its own Delete and Edit functionality. If the GridView is populated with data using an SqlDataSource, checkout the wizard that comes along with the SqlDataSource. It may be used to automatically create an SQL Delete command and specify the delete parameters.

The DataKeyNames property of the GridView is set to a field name of the Table.
       

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
Dot Net - ADO.Net Interview Questions
1 . What is ADO.NET?
ADO.NET is a part of the Microsoft .NET Framework. This framework provides the set of classes that deal with data communication between various layers of the software architecture and the database. It provides a continious access to different data source types such as SQL Server versions 7, 2000, 2005. It also provides connectivity options to data sources through OLE DB and XML. Connectivity may be established with other databases like Oracle, MySQL etc. as well.

ADO.NET has the ability to separate data access mechanisms, data manipulation mechanisms and data connectivity mechanisms.

ADO.NET introduces along with it the disconnected architecture. In a disconncted architecture, data may be stored in a DataSet. It contains providers for connecting to databases, commands for execution and retrieval of results.

The classes for ADO.NET are stored in the DLL System.Data.dll.


2 . What is a connection object in ADO.NET? How to connect to a database in .Net?

A Connection object in ADO.NET is used to establish a connection between a program (the program may be a windows page, a web page, a windows service, a web service etc.) and the database. The connection is open just long enough to get or update data. By quickly opening, then closing a connection, the server resources are used as little as possible. See code below on how to open a connection between UI and database...

'Code below in VB.NET ...
Dim objectConn as SqlClient.SqlConnection
Dim strConn as String
Try
'First, create a connection object
objectConn=New SqlClient.SqlConnection()

'Next, build the Connection String
strConn &="Data Source=(local
strConn &="Initial Catalog=DatabaseName;"
strConn &= "User ID=admin;"
strConn &= "Password=;"

'Note here that the connection string may also be passed as a parameter
'to the connection string object during instantiation

objectConn.ConnectionString = strConn
objectConn.Open() 'Open the Connection

'The connection is now open
'Write your vb.net code here for operations on the database
objectConn.Close()

Catch Ex As Exception
MessageBox.Show(Ex.Message)
End Try
3 . What are Connection Strings
A connection string has a group of semi-colon-separated attributes. Every .Net Data Provider connection string looks different, depending on the type of .NET Data Provider you need to use and which attributes are set for each different type of database system. An example, the connection string below is an example of what you use to connect to a local SQL Server. See that every parameter is separated by a semicolon.

Data Source=(local);Initial Catalog=Northwind;User ID=sa;Password=;

The connection string shown below is an example of how to connect to a Microsoft Access 2000 database using the OleDbConnection object in System.Data.OleDb.

Provider=Microsoft.Jet.OleDb.4.0;Data Source=C:\Northwind.mdb

Parameters in a Connection String - The parameters depend on the data provider is being used.

Server - The name of the SQL Server to which connection has to be established through ADO.NET. This is the name of the system that is running SQL server. We may use "local" or "localhost" for local computer. In case we are using named instances of SQL server, then the parameter would contain the computer name, followed by a backslash, followed by a named instance of the SQL server.

Database - The name of the database to which connection is to be established.

User ID - A user ID configured in the SQL Server by the SQL Server administrator.

Password - As the attribute name suggests, this is the password associated with the user id.

Note that connection string may also contain the Windows NT account security settings. This is done by passing the paramater "integrated security=true".
4 . What is a command object in ADO.NET. How to use a command object in .NET?

ADO.NET Command Object - The Command object is similar to the old ADO command object. It is used to store SQL statements that need to be executed against a data source. The Command object can execute SELECT statements, INSERT, UPDATE, or DELETE statements, stored procedures, or any other statement understood by the database. See sample code...

'Code below in VB.NET ...
Dim ObjCom as SqlClient.SqlCommand
ObjCom.SqlConnection(strCon)
ObjCom.Connection.Open()
ObjCom.CommandText = "Select * from tblSample"
ObjCom.ExecuteNonQuery()

SqlCommand objects are not used much when we use datasets and data adapters. Following are some properties of the SqlCommand class...

Connection Property - This property contains data about the connection string. It must be set on the SqlCommand object before it is executed. For the command to execute properly, the connection must be open at the time of execution.

CommandText Property - This property specifies the SQL string or the Stored Procedure.

objCom.CommandText = "Insert into Employees (empid, empname) values ('EMI0334','Mandy')"

Paramaters Collection - If we want to update values in the Employees table above, but we do not know the values at design time, we make use of placeholders. These are variables prefixed with "@" symbol. Our code will look like this...

objCom.CommandText = "Insert into Employees (empid, empname) values (@empid, @empname)

Next, we have to create parameters that will be used to insert values into the placeholders. For this, we need to add parameters to the parameters collection of the SqlCommand object. This is done so that the values added through the parameters collection & placeholders get i ncluded in the SQL statement. Here, parameters mean the parameters to be passed to the SQL statement/Stored Procedures, not the method's parameters.

In order to add parameters to the SqlCommand object, we write the following code...

objCom.CommandText = "Insert into Employees (empid, empname) values (@empid, @empname)"

objCom.Parameters.Add("@empID", txtempid.text)

objCom.Parameters.Add("@empname", txtempname.text)

ExecuteNonQuery Method - Once the connection is open, we run the query in the SqlCommand object using the ExecuteNonQuery method. This is very simple as shown below...

objConnection.Open()
objCom.ExecuteNonQuery()
objConnection.Close()
5 . What is SelectCommand in ADO.NET?

Select Command Property - This property is used to hold the SQL command that is used to retrieve data from the data source. The CommandText and Connection are properties of the Select Command propety. CommandType is also a property of Select Command. See example below...

Dim da as new SqlDataAdapter
da.SelectCommand = New SqlCommand( )
With da.SelectCommand
.Connection = objConnection
.CommandText = "select * from employees"
End With
6 . What is a SqlCommandBuilder in ADO.NET

SqlCommandBuilder class in ADO.NET provides the feature of reflecting the changes made to a DataSet or an instance of the SQL server data. When an instance of the SqlCommandBuilder class is created, it automatically generates Transact-SQL statements for the single table updates that occur. The object of the SqlCommandBuilder acts as a listener for RowUpdating events, whenever the DataAdapter property is set.

The SqlCommandBuilder object automatically generates the values contained within the SqlDataAdapter's InsertCommand, UpdateCommand and DeleteCommand properties based on the initial SelectCommand. The advantage here is that you will not need to write SqlCommand & SqlParameter Types explicitly.

Basically the command builder object builds these objects on the fly. The command builder object actually reads the metadata of the method called. After the builder object reads the underlying schema of the adapter's method, it autogenerates an underlying insert, update & delete command object. See code example below...

//Code below in C#...
DataSet ds = new DataSet();
SqlConnection cn = new SqlConnection("strSomeConnectionString");
//Autogenerate Insert, Update & Delete commands
SqlDataAdapter da = new SqlDataAdapter("Select from t_Something", cn);
SqlCommandBuilder scb = new SqlCommand(da);

//Fill the dataset
da.Fill(ds,"t_Something");
7 . What is a DataView in ADO.NET?

DataView - Just like we have Views in SQL (in our backend), we have DataView object in ADO.NET. A dataview object represents bindable, customized view of a DataTable object. Operations like Sorting, Filtering, Searching, Editing and Navigation may be performed on a DataView object. In scenarios like retrieval of a subset of data from a Datatable, we may make use of DataViews to get this data. Note that the DefaultView property of a DataTable returns the Default data view for the DataTable. In case a custom view of a DataTable has to be created on a DataView, then the RowFilter property of the DataView is set to the DefaultView.

A dataview may also be used to sort data that resides in it in ascending or descending order. Below is code on how to sort data in a dataview in ascending or descending order...

DataView objdv = new DataView();
objdv.Sort("ColumnName Asc|Desc");
8 . What is DataRelation object in ADO.NET? How to use a DataRelation between two columns in ADO.NET?

In order to set the relationship between two or more than two columns, ADO.NET provides the DataRelation class. When a DataRelation object is created, it assists to enforce some constraints on the relationships between columns. The constraint may be like a Unique constraint that ensures that a column will have no duplicate value in the table. A Foreign Key constraint may be used to enforce Referential Integrity. The Unique property may be set by setting the Unique property of a DataColumn to True. This may also be done by adding an instance of the UniqueConstraint class to the DataRelation object. As a part of the foreign key constraint, we may specify referential integrity rules that are applied at 3 places

1) When a parent record is updated
2) When a parent record is deleted
3) When a change is rejected or accepted.

A DataRelation object permits to establish a parent-child relationship between two or more tables inside a DataSet object. The easiest way to create a DataRelation between two tables in a DataSet is to setup a primary key - foreign key relationship between the columns of a table.

See code example below, where a DataRelation has been setup between the Employee table and the Salary table...

'Code Below in VB.NET
Dim Conn As SqlConnection
Dim da As SqlDataAdapter
Dim ds As DataSet
Dim RowParent As DataRow
Dim RowChild As DataRow

Conn = New _
SqlConnection(ConfigurationSettings.Appsettings("SomeConnectionStringWrittenInWeb.Config"))
da = New SqlDataAdapter("SELECT * FROM Employees", Conn)
ds = New DataSet()

Try
   Conn.Open()
   da.Fill( ds,"Employees")
   da.SelectCommand = New SqlCommand("SELECT * FROM Salary", Conn)
   da.Fill(ds, "Salary")
Catch ex As SqlException
   Response.Write(ex.ToString())
Finally
   Conn.Dispose()
End Try

'Next, Let us create a Data Relationship
ds.Relations.Add("Employee_Salary", ds.Tables("Employees").Columns("EmployeeID"), _
ds.Tables("Salary").Columns("EmployeeID"))
'Display the Employee and Child Salary in the Form
'Say we have a Label in the form
For each RowParent in ds.Tables("Employees").Rows

   lblRelation.Text &= RowParent("Emp_Name")
   For each RowChild in RowParent.GetChildRows("Employee_Salary")
     lblRelation.Text &= "<br/>" & RowChild("Sal_Amount")
   Next
Next
9 . What is Diffgram in ADO.NET? When do we use Diffgram?
A DiffGram is an XML format. It is used to identify current and original versions of data elements. A DataSet may use a DiffGram format to load and persist the contents, and further to serialize its contents for porting across a network connection. Whenever a DataSet is written as a DiffGram, the DataSet populates the DiffGram with all the important information to accurately recreate the contents. Note that schema of the DataSet is not recreated. This includes column values from both the Current and the Original row versions, row error information, and row order.
10 . What is a Typed Dataset in ADO.NET? Why do we use a Typed DataSet? What is the difference between a Typed and an UnTyped DataSet?
Typed DataSet - When a created DataSet derives from the DataSet class, that applies the information contained in the XSD to create a Typed class, this DataSet is said to be a Typed Dataset. Information from the schema whic comprises the tables, columns, and rows is created and compiled to a new DataSet derived from the XSD. The Typed DataSet class features all functionality of the DataSet class. This may be used with methods that take an instance of the DataSet class as a parameter.

Note that an UnTyped DataSet does not have any schema. It is exposed simply as a mere collection.

How to create a Typed DataSet? -
Write click your project in the Solution Explorer.
Click Add New Item.
Select DataSet.

This adds a new XSD to the project. The schema created may be viewed as an XML. When this xsd file is compiled, two files are created by Visual Studio. The first file that contains the .vb or .cs extension contains the information about the proxy class. This class contains methods & properties that are required to access the database data. The second file has an extension xsx and this contains information about the layout of the XSD.
11 . How to run a stored procedure from .NET code?

Use the Command object and its ExecuteNonQuery method to run a DDL or DCL statement of SQL. First, create a connection object and a command object, and configure these objects for the statement you wish to execute. Open the database connection. Call ExecuteNonQuery on the command. Close the connection.

Example
Suppose we have to insert FirstName into a table t_Employees. Our Store procedure is:

Create Procedure dbo.InsertFirstName
(
@FirstName varchar(30)
)
as
Insert Into t_Employees values (@FirstName)

VB.NET code below, to pass FirstName to this Stored Procedure

Dim cmRunProc as New SqlCommand("dbo.InsertFirstName", objCon)
cmRunProc.CommandType = CommandType.StoredProcedure
cmRunProc.Parameters.Add("@FirstName", txtFirstName.Text)
objCon.Open()
cmdRunProc.ExecuteNonQuery()
objCon.Close()
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
       ADO .NET
------------

Previous Technology: ADO Object [Connection Oriented Technology]
Latest Technology: ADO .NET [Disconnected Data Architecture]

Database Providers:
-----------------------

1) Odbc    [System.Data.Odbc]
2) OleDb   [System.Data.OleDb]
3) Sql        [System.Data.SqlClient]
4) Oracle   [System.Data.OracleClient]

Components of ADO .NET
------------------------------
1) Connection
2) DataAdapter
3) CommandBuilder
4) DataSet
     i) DataTable
    ii) DataColums
   iii) DataRow
5) Command
6) DataReader

1) Connection
       - OdbcConnection
       - OleDbConnection
       - SqlConnection
       - OracleConnection

        OdbcConnection cn=new OdbcConnection("dsn=ajay;uid=xxx;pwd=xxx");

        OleDbConnection cn=new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Scott.mdb;Persist Security Info=False");

        SqlConnection cn=new SqlConnection("Data Source=.\SQLEXPRESS;Initial Catalog=scott;Integrated Security=true");

        OracleConnection cn=new OracleConnection("user id=scott;password=tiger");

2) DataAdapter
          --OdbcDataAdapter
          --OleDbDataAdapter
          --SqlDataAdapter
          --OracleDataAdapter

          SqlDataAdapter ada=new SqlDataAdapter("select * from dept",cn);

3) CommandBuilder
          --OdbcCommandBuilder
          --OleDbCommandBuilder
          --SqlCommandBuilder
          --OracleCommandBuilder

          SqlCommandBuilder cmb=new SqlCommandBuilder(ada);

4) DataSet

        DataSet ds=new DataSet();
        ada.fill(ds,"Dept");
        ada.update(ds,"Dept");

5) Command
         --OdbcCommand
         --OleDbCommand
         --SqlCommand
         --OracleCommand

          Select- SingleValueQuery  -- ExecuteScalar()
                     - MultiValueQuery  --ExecuteReader()

        Insert    ---
        Update  -----> ExecuteNonQuery();
        Delete   ---

        SqlCommand cmd=new SqlCommand("insert into dept values(10,'Sales','Lucknow')",cn);
        cn.open();
        cmd.ExecuteNonQuery();
        cn.close();

        SqlCommand cmd=new SqlCommand("updae dept set dname='Sales',loc='Kanpur' where deptno=10",cn);
        cn.open();
        cmd.ExecuteNonQuery();
        cn.close();

        SqlCommand cmd=new SqlCommand("delete from dept where deptno=20",cn);
        cn.open();
        cmd.ExecuteNonQuery();
        cn.close();

        SqlCommand cmd=new SqlCommand("select max(deptno) from dept",cn);
        cn.open();
        int mdno=Convert.ToInt32(cmd.ExecuteScalar());
        cn.close();

6) DataReader
       --OdbcDataReader
       --OleDbDataReader
       --SqlDataReader
       --OracleDataReader

      SqlCommand cmd=new SqlCommand("select deptno,dname from dept",cn);
      cn.open();
      SqlDataReader rd=cmd.ExecuteReader(CommandBehaviour.CloseConnection);
      while(rd.Read())
      {
        cmbDept.items.add(String.format("{0} ({1})",rd[1],rd[0]));
      }
      rd.close();
     














       






Featured post

Life Infotech now a leading brand in the field of technology training

  Life Infotech now a leading brand in the field of technology training & its invites students around the nation to be a part of the Tra...