Академический Документы
Профессиональный Документы
Культура Документы
1 . What is .NET?
.NET is a general-purpose software development platform, similar to Java. At its core
is a virtual machine that turns intermediate language (IL) into machine code. High-level
language compilers for C#, VB.NET and C++ are provided to turn source code into IL. C#
is a new programming language, very similar to Java. An extensive class library is
included, featuring all the functionality one might expect from a contempory development
platform - windows GUI development (Windows Forms), database access (ADO.NET), web
development (ASP.NET), web services, XML etc
.NET 1.1 was released in April 2003, and was mostly bug fixes for 1.0.
.NET 2.0 was released to MSDN subscribers in late October 2005, and was officially
launched in early November.
IIS is not supported on Windows XP Home Edition, and so cannot be used to host
ASP.NET. However, the ASP.NET Web Matrixweb server does run on XP Home
The .NET Compact Framework is a version of the .NET Framework for mobile devices,
running Windows CE or Windows Mobile.
The Mono project has a version of the .NET Framework that runs on Linux.
• The .NET Framework SDK is free and includes command-line compilers for C++, C#,
and VB.NET and various other utilities to aid development.
• SharpDevelop is a free IDE for C# and VB.NET.
• Microsoft Visual Studio Express editions are cut-down versions of Visual Studio, for
hobbyist or novice developers.There are different versions for C#, VB, web
development etc. Originally the plan was to charge $49, but MS has decided to offer
them as free downloads instead, at least until November 2006.
• Microsoft Visual Studio Standard 2005 is around $300, or $200 for the upgrade.
• Microsoft VIsual Studio Professional 2005 is around $800, or $550 for the upgrade
• At the top end of the price range are the Microsoft Visual Studio Team Edition for
Software Developers 2005 with MSDN Premium and Team Suite editions.
You can see the differences between the various Visual Studio versions here.
8 . What is IL?
IL = Intermediate Language. Also known as MSIL (Microsoft Intermediate Language)
or CIL (Common Intermediate Language). All .NET source code (of any language) is
compiled to IL during development. The IL is then converted to machine code at the point
where the software is installed, or (more commonly) at run-time by a Just-In-Time (JIT)
compiler.
9 . What is C#?
C# is a new language designed by Microsoft to work with the .NET framework. In
their "Introduction to C#" whitepaper, Microsoft describe C# as follows:
Substitute 'Java' for 'C#' in the quote above, and you'll see that the statement still
works pretty well :-).
Managed code: The .NET framework provides several core run-time services to the
programs that run within it - for example exception handling and security. For these
services to work, the code must provide a minimum level of information to the runtime.
Such code is called managed code.
Managed data: This is data that is allocated and freed by the .NET runtime's garbage
collector.
11 . What is an assembly?
An assembly is sometimes described as a logical .EXE or .DLL, and can be
an application (with a main entry point) or alibrary. An assembly consists of one or
more files (dlls, exes, html files etc), and represents a group of resources, type definitions,
and implementations of those types. An assembly may also contain references to other
assemblies. These resources, types and references are described in a block of data called
a manifest. The manifest is part of the assembly, thus making the assembly self-
describing.
An important aspect of assemblies is that they are part of the identity of a type. The
identity of a type is the assembly that houses it combined with the type name. This
means, for example, that if assembly A exports a type called T, and assembly B exports a
type called T, the .NET runtime sees these as two completely different types. Furthermore,
don't get confused between assemblies and namespaces - namespaces are merely a
hierarchical way of organising type names. To the runtime, type names are type names,
regardless of whether namespaces are used to organise the names. It's the assembly plus
the typename (regardless of whether the type name belongs to a namespace) that
uniquely indentifies a type to the runtime.
Assemblies are also important in .NET with respect to security - many of the security
restrictions are enforced at the assembly boundary.
Finally, assemblies are the unit of versioning in .NET - more on this below.
You can then view the contents of the assembly by running the "IL Disassembler"
tool that comes with the .NET SDK.
Alternatively you can compile your source into modules, and then combine the
modules into an assembly using the assembly linker (al.exe). For the C# compiler, the
/target:module switch is used to generate a module instead of an assembly.
Assemblies deployed to the GAC must be strong-named. Outside the GAC, strong-
naming is optional.
For strongly named assemblies, the version of a referenced assembly is stored in the
referring assembly, and by default only this exact version will be loaded at run-time. If the
exact version is not available, the referring assembly will fail to load. It is possible to
override this behaviour in the config file for the referring assembly - references to a single
version or a range of versions of the referenced assembly can be redirected to a specific
version. For example, versions 1.0.0.0 to 2.0.0.0 can be redirected to version 3.0.125.3.
However note that there is no way to specify a range of versions to be redirected to.
Publisher policy files offer an alternative mechanism for redirecting to a different version
for assemblies deployed to the GAC - a publisher policy file allows the publisher of the
assembly to redirect all applications to a new version of an assembly in one operation,
rather than having to modify all of the application configuration files.
The restrictions on version policy for strongly named assemblies can cause problems
when providing patches or 'hot fixes' for individual assemblies within an application. To
avoid having to deploy config file changes or publisher policy files along with the hot fix, it
makes sense to reuse the same assembly version for the hot fix. If desired, the assemblies
can be distinguised by altering the assembly file version, which is not used at all by the
CLR for applying version policy. For more discussion, see Suzanne Cook's When to Change
File/Assembly Versions blog entry.
Note that the versioning of strongly named assemblies applies whether the
assemblies are deployed privately or to the GAC.
Win32 processes provide isolation by having distinct memory address spaces. This is
effective, but expensive. The .NET runtime enforces AppDomain isolation by keeping
control over the use of memory - all memory in the AppDomain is managed by the .NET
runtime, so the runtime can ensure that AppDomains do not access each other's memory.
One non-obvious use of AppDomains is for unloading types. Currently the only way to
unload a .NET type is to destroy the AppDomain it is loaded into. This is particularly useful
if you create and destroy types on-the-fly via reflection.
20 . Is it true that objects don't always get destroyed immediately when the
last reference goes away?
Yes. The garbage collector offers no guarantees about the time when an object will
be destroyed and its memory reclaimed.&
There was an interesting thread on the DOTNET list, started by Chris Sells, about the
implications of non-deterministic destruction of objects in C#. In October 2000, Microsoft's
Brian Harry posted a lengthy analysis of the problem. Chris Sells'response to Brian's
posting is here
For the first category, it makes sense to implement IDisposable and override
Finalize. This allows the object user to 'do the right thing' by calling Dispose, but also
provides a fallback of freeing the unmanaged resource in the Finalizer, should the calling
code fail in its duty. However this logic does not apply to the second category of class,
with only managed resources. In this case implementing Finalize is pointless, as managed
member objects cannot be accessed in the Finalizer. This is because there is no guarantee
about the ordering of Finalizer execution. So only the Dispose method should be
implemented. (If you think about it, it doesn't really make sense to call Dispose on
member objects from a Finalizer anyway, as the member object's Finalizer will do the
required cleanup.)
For classes that need to implement IDisposable and override Finalize, see
Microsoft's documented pattern.
Note that some developers argue that implementing a Finalizer is always a bad idea,
as it hides a bug in your code (i.e. the lack of a Dispose call). A less radical approach is to
implement Finalize but include a Debug.Assert at the start, thus signalling the problem in
developer builds but allowing the cleanup to occur in release builds.
Also there is a gcConcurrent setting that can be specified via the application
configuration file. This specifies whether or not the garbage collector performs some of its
collection activities on a separate thread. The setting only applies on multi-processor
machines, and defaults to true.
This situation causes two problems. The obvious problem is the leakage of the
subscriber object. The other problem is the performance degredation due to the publisher
sending redundant notifications to 'zombie' subscribers.
There are at least a couple of solutions to the problem. The simplest is to make sure
the subscriber is unsubscribed from the publisher, typically by adding an Unsubscribe()
method to the subscriber. Another solution, documented here by Shawn Van Ness, is to
change the publisher to use weak references in its subscriber list.
27 . What is serialization?
Serialization is the process of converting an object into a stream of bytes.
Deserialization is the opposite process, i.e. creating an object from a stream of bytes.
Serialization/Deserialization is mostly used to transport objects (e.g. during remoting), or
to persist objects (e.g. to a file or database).
For example, using the default security policy, a control downloaded from a web site
belongs to the 'Zone - Internet' code group, which adheres to the permissions defined by
the 'Internet' named permission set. (Naturally the 'Internet' named permission set
represents a very restrictive range of permissions.)
37 . I'm having some trouble with CAS. How can I troubleshoot the problem?
Caspol has a couple of options that might help. First, you can ask caspol to tell you
what code group an assembly belongs to, using caspol -rsg. Similarly, you can ask what
permissions are being applied to a particular assembly using caspol -rsp
38 . I can't be bothered with CAS. Can I turn it off?
Yes, as long as you are an administrator. Just run:
caspol -s off
Of course if you are writing web services then reverse-engineering is not a problem
as clients do not have access to your IL.
class MainApp
{
[DllImport("user32.dll", EntryPoint="MessageBox", SetLastError=true,
CharSet=CharSet.Auto)]
public static extern int MessageBox(int hWnd, String strMessage, String
strCaption, uint uiType);
int m_size = 0;
}
The use of 'yield return' is rather strange at first sight. It effectively synthethises an
implementation of IEnumerator, something we had to do manually in .NET 1.x.
68 . What's the problem with .NET generics?
.NET generics work great for container classes. But what about other uses? Well,
it turns out that .NET generics have a major limitation - they require the type
parameter to be constrained. For example, you cannot do this:
static class Disposer<T>
{
public static void Dispose(T obj) { obj.Dispose(); }
}
The C# compiler will refuse to compile this code, as the type T has not been
constrained, and therefore only supports the methods of System.Object. Dispose is
not a method on System.Object, so the compilation fails. To fix this code, we need to
add a where clause, to reassure the compiler that our type T does indeed have a
Dispose method
static class Disposer<T> where T : IDisposable
{
public static void Dispose(T obj) { obj.Dispose(); }
}
The problem is that the requirement for explicit contraints is very limiting. We can use
constraints to say that T implements a particular interface, but we can't dilute that to
simply say that T implements a particular method. Contrast this with C++ templates
(for example), where no constraint at all is required - it is assumed (and verified at
compile time) that if the code invokes the Dispose() method on a type, then the type
will support the method.
In fact, after writing generic code with interface constraints, we quickly see that we
haven't gained much over non-generic interface-based programming. For example,
we can easily rewrite the Disposer class without generics:
static class Disposer
{
public static void Dispose( IDisposable obj ) { obj.Dispose(); }
}
For more on this topic, start by reading the following articles:
Bruce Eckel: http://www.mindview.net/WebLog/log-0050
Ian Griffiths: http://www.interact-sw.co.uk/iangblog/2004/03/14/generics
Charles Cook: http://www.cookcomputing.com/blog/archives/000425.html
69 . What's new in the .NET 2.0 class library?
Here is a selection of new features in the .NET 2.0 class library:
• Generic collections in the System.Collections.Generic namespace.
• The System.Nullable<T> type. (Note that C# has special syntax for this type, e.g.
int? is equivalent to Nullable<int>)
• The GZipStream and DeflateStream classes in the System.IO.Compression
namespace.
• The Semaphore class in the System.Threading namespace.
• Wrappers for DPAPI in the form of the ProtectedData and ProtectedMemory classes
in the System.Security.Cryptography namespace.
• The IPC remoting channel in the System.Runtime.Remoting.Channels.Ipc
namespace, for optimised intra-machine communication.
and many, many more. See http://msdn2.microsoft.com/en-us/library/t357fb32(en-
US,VS.80).aspx for a comprehensive list of changes.
38 . What is ViewState?
ViewState allows the state of objects (serializable) to be stored
in a hidden field on the page. ViewState is transported to the client
and back to the server, and is not stored on the server or any other
external source. ViewState is used the retain the state of server-
side objects between postabacks.
39 . What is the lifespan for items stored in ViewState?
Item stored in ViewState exist for the life of the current page.
This includes postbacks (to the same page).
40 . What does the "EnableViewState" property do? Why
would I want it on or off?
It allows the page to save the users input on a form across
postbacks. It saves the server-side values for a given control into
ViewState, which is stored as a hidden value on the page before
sending the page to the clients browser. When the page is posted
back to the server the server control is recreated with the state
stored in viewstate.
41 . What are the different types of Session state
management options available with ASP.NET?
ASP.NET provides In-Process and Out-of-Process state
management. In-Process stores the session in memory on the web
server. This requires the a "sticky-server" (or no load-balancing) so
that the user is always reconnected to the same web server. Out-of-
Process Session state management stores data in an external data
source. The external data source may be either a SQL Server or a
State Server service. Out-of-Process state management requires
that all objects stored in session are serializable.
42 . Let's say I have an existing application written using
Visual Studio 6 (VB 6, InterDev 6) and this application utilizes
Windows 2000 COM+ transaction services. How would you
approach migrating this application to .NET
You have to use System.EnterpriseServices namespace and also
COMInterop the existing application
43 . Can you give an example of what might be best suited to
place in the Application_Start and Session_Start subroutines?
In the Application_Start event you could store the data, which
is used throughout the life time of an application for example
application name, where as Session_Start could be used to store the
information, which is required for that session of the application say
for example user id or user name.
44 . If I'm developing an application that must accomodate
multiple security levels though secure login and my ASP.NET
web appplication is spanned across three web-servers (using
round-robbin load balancing) what would be the best
approach to maintain login-in state for the users?
Use the state server or store the state in the database. This can
be easily done through simple setting change in the web.config.
<sessionState
mode="InProc"
stateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString="data source=127.0.0.1;user
id=sa;password="
cookieless="false"
timeout="30"
/>
in the above one instead of mode="InProc", you specifiy stateserver
or sqlserver.
45 . What are ASP.NET Web Forms? How is this technology
different than what is available though ASP (1.0-3.0)?
ASP.NET webforms are analogous to Windows Forms which are
available to most VB developers. A webform is essentially a core
container in a Page. An empty webform is nothing but a HTML Form
tag(control) running at server and posting form to itself by default,
but you could change it to post it to something else. This is a
container, and you could place the web controls, user controls and
HTML Controls in that one and interact with user on a postback
basis.
46 . How does VB.NET/C# achieve polymorphism?
Polymorphism is achieved through virtual, overloaded,
overridden methods in C# and VB.NET
47 . Describe session handling in a webform, how does it
work and what are the its limits
Out of all the Page_Load is the one where your code gets loaded and
your magic should be written. page_init
occurs only once, i.e. when the page is initially created.
Array
? Insertion or deletion of element at any position require a linear
(O(n)) number of operations.
? Poor at deleting nodes (or elements) as it cannot remove one node
without individually shifting all the elements up the list by one.,
O(n)
? Poor at inserting as an array will eventually either fill up or need to
be resized, an expensive operation that may not even be possible if
memory is fragmented. Similarly, an array from which many
elements are removed may become wastefully empty or need to be
made smaller, O(n)
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.
(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
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
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 ActiveServer 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.
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 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
50 . What is the difference between Absolute vs Relative URLs?
Absolute /Fully Qualified URLs:
• Contain all information necessary for the browser(or other client program) to locate
the resource named in the URL
o This includes protocol moniker used( i.e http://, ftp://..etc..), Server's Domain
name or IP address and the file path
o Absolute URL looks as http://localhost/megasolutions/page1.aspx
Relative URLs:
URI is the more generic term, and a URL is a particular type of URI in that a URL has
to uniquely identify some resource on the Web.
2 . How to convert milliseconds into time?
VB.NET
dim ts as TimeSpan = TimeSpan.FromMilliseconds(10000)
Response.Write (ts.ToString () )
C#
TimeSpan ts = TimeSpan.FromMilliseconds(10000);
Response.Write (ts.ToString () );
3 . How to include multiple vb/cs files in the source?
You can do this using assembly directives.
<%@ assembly src="test1.vb" %>
<%@ assembly src="test2.vb" %>
or
<%@ assembly src="test1.cs" %>
<%@ assembly src="test2.cs" %>
However, note that each source file will be compiled individually into its own assembly,
so they cannot have dependencies on each other.
4 . How to convert a string to Proper Case?
Use the namespace System.Globalization
VB.NET
Dim myString As String = "syncFusion deVeloPer sUppOrt"
' Creates a TextInfo based on the "en-US" culture.
Dim TI As TextInfo = New CultureInfo("en-US", False).TextInfo
Response.Write(TI.ToTitleCase(myString))
C#
string myString = "syncFusion deVeloPer sUppOrt";
// Creates a TextInfo based on the "en-US" culture.
TextInfo TI = new CultureInfo("en-US",false).TextInfo;
Response.Write (TI.ToTitleCase( myString ));
C#
Response.Write("<script>alert('Hello');</script>") ;
7 . How to validate that a string is a valid date?
VB.NET
Dim blnValid As Boolean = False
Try
DateTime.Parse(MyString)
blnValid = True
Catch
blnValid = False
End Try
C#
bool blnValid=false;
try
{
DateTime.Parse(MyString);
blnValid=true;
}
catch
{
blnValid=false;
}
8 . Are namespaces and Class names Case Sensitive?
Namespaces and Class names are case Sensitive. Namespaces imported using the @
Import Directive will cause an error if the correct case is not used.
9 . How to convert string to a DateTime and compare it with another DateTime?
VB.NET
Dim blntimeIsOk As Boolean = DateTime.Parse("15:00") < DateTime.Parse("08:00")
Response.Write(blntimeIsOk)
C#
bool blntimeIsOk = (DateTime.Parse("15:00") < DateTime.Parse("08:00"));
Response.Write (blntimeIsOk);
10 . How to get the url of page dynamically?
Use Request.Url property
11 . How to convert user input in dMy format to Mdy?
VB.NET
Dim dt As DateTime = DateTime.ParseExact("0299", New String() {"My", "M/y"}, Nothing,
System.Globalization.DateTimeStyles.None)
C#
DateTime dt = DateTime.ParseExact("0299", new string[] {"My","M/y"},
null,System.Globalization.DateTimeStyles.None);
• Tranfers the page control to the other page, in other words it sends the request to
the other page.
• Causes the client to navigate to the page you are redirecting to. In http terms it
sends a 302 response to the client, and the client goes where it's told.
Server.Transfer
• Only transfers the execution to another page and during this you will see the URL of
the old page since only execution is transfered to new page and not control.
• Occurs entirely on the server, no action is needed by the client
• HttpContext.Current.Server.MachineName
• HttpContext.Current.Request.ServerVariables["LOCAL_ADDR"]
The first one should return the name of the machine, the second returns the local ip
address.
Note that name of the machine could be different than host, since your site could be using
host headers
18 . What is the meaning of validateRequest=true in .net framework1.1?
The value of validateRequest is set to 'true' by default, which means that the
framework will automatically deny submission of the '<' and '>' characters.
19 . What is the different between and ?
The <%# %> is used for databinding where as <%= %> is used to output the result of
an expression. The expression inside <%# %> will be executed only when you call the
page's or control's DataBind method. The expression inside <%= %> will be executed and
displayed as and when it appears in the page.
20 . What permissions do ASP.NET applications posses by default?
By default ASP.NET Web applications run as ASP.NET user. This user has limited
permissions equivalent to the User Group.
21 . How can I specify the relative path for a file?
Suppose you have following file hierarchy:
default.aspx
Admin/login.aspx
Misc/testpage.aspx
And you are on the login.aspx and want your user to navigate to the default.aspx (or
testpage.aspx) file. Then you can use
• Response.Redirect ("../default.aspx")
• Response.Redirect ("../Misc/testpage.aspx")
22 . How can I specify the "upload a file" input textbox in a form to be read only
so that the user can click on the browse button and pick a file but they cannot
type anything into the textbox next to the browse button.
<input id="File1" type="file" contenteditable=false />
23 . How to change the Page Title dynamically?
<TITLE id="Title1" runat =server ></TITLE>
VB.NET
'Declare
Protected WithEvents Title1 As System.Web.UI.HtmlControls.HtmlGenericControl
'In Page_Load
Title1.InnerText ="Page 1"
C#
//Declare
protected System.Web.UI.HtmlControls.HtmlGenericControl Title1 ;
//In Page_Load
Title1.InnerText ="Page 1" ;
24 . Why do I get the error message "Object must implement IConvertible". How
can I resolve it?
The common cause for this error is specifying a control as a SqlParameter's Value
instead of the control's text value.
For example, if you write code as below you'll get the above error:
VB.NET
Dim nameParameter As SqlParameter = command.Parameters.Add("@name",
SqlDbType.NVarChar, 50)
nameParameter.Value = txtName
C#
SqlParameter nameParameter = command.Parameters.Add("@name", SqlDbType.NVarChar,
50);
nameParameter.Value = txtName ;
To resolve it, specify the control's Text property instead of the control itself.
VB.NET
nameParameter.Value = txtName.Text
C#
nameParameter.Value =txtName.Text;
25 . Why is default.aspx page not opened if i specify http://localhost. I am able
to view this page if i hardcode it as http://localhost/default.aspx?
If some other default page comes higher in the list, adjust the default.aspx to be the
number one entry inside the IIS configuration. If you have multiple websites inside IIS,
make sure the configuration is applied on the right website (or on all websites by applying
the configuration on the server-level using the properties dialog, configure WWW service).
26 . Can ASP.NET work on an NT server?
No. For more details refer ASP 1.1 version
27 . Is it possible to migrate Visual InterDev Design-Time Controls to ASP.NET?
Refer INFO: Migrating Visual InterDev Design-Time Controls to ASP.NET
28 . How to automatically get the latest version of all the asp.net solution items
from Source Safe when opening the solution?
In VS.NET you can go to Tools > Options > Source Control > General and check the
checkbox for Get everything when a solution opens.
This retrieves the latest version of all solution items when you open the solution.
29 . How to make VS.Net use FlowLayout as the default layout rather than the
GridLayout?
For VB.NET, go to path C:\Program Files\Microsoft Visual Studio
.NET\Vb7\VBWizards\WebForm\Templates\1033
Change the following line in the existing WebForm1.aspx
<body MS_POSITIONING="[!output DEFAULT_HTML_LAYOUT]">
to
For C#, go to path C:\Program Files\Microsoft Visual Studio .NET
2003\VC#\VC#Wizards\CSharpWebAppWiz\Templates\1033
Change the following line in the existing WebForm1.aspx
<body MS_POSITIONING="[!output DEFAULT_HTML_LAYOUT]">
to
Note:Before changing any templates it's a good idea to make backup copies of them
Or rather than above approach you can change the behavior for new files on a per project
basis in Visual Studio by:
1. Right clicking on the project name (Ex: "WebApplication1)" in Solution Explorer, and
select "Properties".
2. From project properties window, under Common Properties>Designer Defaults>Page
Layout change "Grid" to "Flow".
C#
double Telno= double.Parse(ds.Tables[0].Rows[0]["TelNo"].ToString());
Response.Write(Telno.ToString("###-###-####"));
32 . Can two different programming languages be mixed in a single ASPX file?
No. ASP.NET uses parsers to strip the code from ASPX files and copy it to temporary
files containing derived Page classes, and a given parser understands only one language
33 . Can I use custom .NET data types in a Web form?
Yes. Place the DLL containing the type in the application root's bin directory and
ASP.NET will automatically load the DLL when the type is referenced. This is also what
happens when you add a custom control from the toolbox to your web form.
34 . How can I have a particular Web page in an ASP.NET application which
displays its own error page.
This can be done by setting the ErroPage attribute of Page Directive or ErrorPage
property of Page Class to the desired Custom Error Page
<%@Page Language="C#" ErrorPage="specificerropage.htm"%>
In web.config
<customErrors mode="On" />
Class Questions
17 . What is the syntax to inherit from a class in C#?
Place a colon and then the name of the base class.
Example: class MyNewClass : MyBaseClass
18 . Can you prevent your class from being inherited by
another class?
Yes. The keyword “sealed” will prevent the class from being
inherited.
19 . Can you allow a class to be inherited, but prevent the
method from being over-ridden?
Yes. Just leave the class public and make the method
sealed.
20 . What’s an abstract class?
A class that cannot be instantiated. An abstract class is a
class that must be inherited and have the methods overridden.
An abstract class is essentially a blueprint for a class without any
implementation.
21 . When do you absolutely have to declare a class as
abstract?
1. When the class itself is inherited from an abstract class,
but not all base abstract methods have been overridden.
2. When at least one of the methods in the class is
abstract.
22 . What is an interface class?
Interfaces, like classes, define a set of properties, methods,
and events. But unlike classes, interfaces do not provide
implementation. They are implemented by classes, and defined
as separate entities from classes.
23 . Why can’t you specify the accessibility modifier for
methods inside the interface?
They all must be public, and are therefore public by default.
24 . Can you inherit multiple interfaces?
Yes. .NET does support multiple interfaces.
25 . What happens if you inherit multiple interfaces and
they have conflicting method names?
It’s up to you to implement the method inside your own
class, so implementation is left entirely up to you. This might
cause a problem on a higher-level scale if similarly named
methods from different interfaces expect different data, but as
far as compiler cares you’re okay.
To Do: Investigate
26 . What’s the difference between an interface and
abstract class?
In an interface class, all methods are abstract - there is no
implementation. In an abstract class some methods can be
concrete. In an interface class, no accessibility modifiers are
allowed. An abstract class may have accessibility modifiers.
27 . What is the difference between a Struct and a Class?
Structs are value-type variables and are thus saved on the
stack, additional overhead but faster retrieval. Another
difference is that structs cannot inherit.
Assembly Questions
55 . How is the DLL Hell problem solved in .NET?
Assembly versioning allows the application to specify not
only the library it needs to run (which was available under
Win32), but also the version of the assembly.
56 . What are the ways to deploy an assembly?
An MSI installer, a CAB archive, and XCOPY command.
57 . What is a satellite assembly?
When you write a multilingual or multi-cultural application in
.NET, and want to distribute the core application separately from
the localized modules, the localized assemblies that modify the
core application are called satellite assemblies.
58 . What namespaces are necessary to create a localized
application?
System.Globalization and System.Resources.
59 . What is the smallest unit of execution in .NET?
An Assembly.
60 . When should you call the garbage collector in .NET?
As a good rule, you should not call the garbage collector.
However, you could call the garbage collector when you are done
using a large object (or set of objects) to force the garbage
collector to dispose of those very large objects from memory.
However, this is usually not a good practice.
61 . How do you convert a value-type to a reference-type?
Use Boxing.
62 . What happens in memory when you Box and Unbox a
value-type?
Boxing converts a value-type to a reference-type, thus
storing the object on the heap. Unboxing converts a reference-
type to a value-type, thus storing the value on the stack.