Download - DotNet Questions and Answers
-
8/9/2019 DotNet Questions and Answers
1/27
PLEXIAN SOFTWARE SOLUTIONS PVT. LTD. (.NET)
Time: 45 Mins
All the answeres should not more than 7 sentences.
ASP.NET
Explain Server side code and Client side code?Difference between ADO.net Dataset and ADO recordset?Define inline and code behind? Which is best?In what order do the events ofan ASPX page Execute?Dataset, Repeater and List control Difference?What method do you use to explicitly kill a user Session?Difference between HTML control and Web control and Server control?Difference Between Global.asax and web.config file?Difference between Trace and Debug?In ASP.NET we have .aspx file and HTML file which file execute first explain
C#
what is Boxing and Unboxind. Give Example.What are the fundamental difference between value type and reference type?Are C# Destructors the same as C++ Destructors? Example.Define Delegates?Does C# Support a Variable Number of Arguments?How can I process command-line Arguments?What is Key Qualifier?Explain Shadowing?
Explain and give an example of Finally?What is GAC? Define.
VB.NET and Database
Explain About Two-Tier, Three-Tier and N-Tier System?Overview: VPN?Overview: RCW and CCW?Difference between Typed data set and Untyped data set?Difference between Clustered Index and Non-Clustered index?What is Function, View and Stored procedure in SQL Server 2000?What is Trigger? Which is new in SQL Server 2000?
Define. char, varchar, text, nvarchar and ntext?What is patindex and charindex?What is Stuff in SQL server 2000?
-
8/9/2019 DotNet Questions and Answers
2/27
ASP.NET
Explain Server side code and Client side code?
Server side code: That code talk to server side like database access.
Client side code: That code is like VB / Java scripts. It is to use validation purpose.
Difference between ADO.net Dataset and ADO recordset?
ADO.NET Datasets
Datasets are containers caches in which you can store data to use in yourapplication. Datasets are a fundamental part of the ADO.NET architecture, providing both
high-performance data access as well as scalability.
1.Adding Tables to an Existing Dataset2.Adding Existing Typed Datasets to a Form or Component
3.Adding Untyped Datasets to a Form or Component
4.Walkthrough: Mapping Data Source Tables to Dataset Tables
The following code examples show how to load a DataSet from an XML stream. The firstexample shows a file name being passed to the ReadXml method. The second example shows a
string that contains XML being loaded using a System.IO.StringReader.
[C#]DataSet myDS = new DataSet();myDS.ReadXml("input.xml", XmlReadMode.ReadSchema);
Accessing an ADO Recordset or Record from ADO.NET
In the .NET Framework, you can access existing components that return ADO Recordset orRecord objects, and you can also access ADO Recordset and Record objects directly using theOLE DB .NET Data Provider. The OLE DB .NET Data Provider supports filling a DataSet from anADO Recordset or Record. This enables you to consume existing Component Object Model (COM)objects that return ADO objects, without having to rewrite them entirely using the .NET Framework.
dim rs as new adodb.recordsetrs.cursorlocation = adUseClientrs.open "select * from products", "DSN=advWorks", adOpenStatic, adLockOptimistic
Define inline and code behind? Which is best?
Inline
Defines inline code or inline expressions that execute when the page is rendered.
There are two styles: inline code and inline expressions. Use inline code to define self-contained code blocks or control flow blocks
-
8/9/2019 DotNet Questions and Answers
3/27
Example
The following example shows how you can use the render blocks to display the sameHTML text in a number of different font sizes.
[C#]
Hello World!
[Visual Basic]
Hello World!
Just as you can create Web Forms pages using code-behind files separating the UIsyntax (in the .aspx file) from the logic that the page performs (the code-behind file) you can dothe same to create user controls. The techniques are the same, with some minor differences.
Note If you are using a RAD tool to create your ASP.NET applications, such asVisual Studio .NET, the tool's default is to use code-behind techniques to build user
controls and Web Forms pages.
To develop user controls in a code-behind file
1. Create a code-behind file that includes the namespaces that your user control will need
to access. At a minimum you should include the System and the System.Web.UInamespaces, along with any other namespaces that your user control requires.
[C#]using System;using System.Web.UI;
using System.Web.UI.WebControls;
[Visual Basic]Imports SystemImports System.Web.UIImports System.Web.UI.WebControls
2. Declare a class that inherits from the UserControl class and write code to give it the
functionality you want. Include any event-handling methods that you write for the user
control. Also, declare public instances of the ASP.NET server controls that you plan touse in the user control.
[C#]public class MyCodeBehind : UserControl {public TextBox Name;public Label Result;
public void SubmitBtn_Click(Object sender, EventArgs e)
-
8/9/2019 DotNet Questions and Answers
4/27
{Result.Text = "Hi, " + Name.Text + ", welcome to ASP.NET!";
}}
[Visual Basic]Public Class MyCodeBehindInherits UserControl
Public Name As TextBoxPublic Result As Label
Public Sub SubmitBtn_Click(sender As Object, e As EventArgs)Result.Text = "Hi, " & Name.Text & ", welcome to ASP.NET!"
End SubEnd Class
3. Name the code-behind file, making sure to include an extension that reflects the
language in which you developed the file. If you do not do this, a compiler error will
occur. In this example, the user control developed in Visual Basic is namedUserControl.vb, and the one developed in C# is named UserControl.cs.
4. Create an .ascx file, using the @ Control directive to indicate the name of the class the
user control inherits and the path to the source file you created in Step 1. Include theserver controls and any text that you want the user control to display. When you declare
the ID attribute on each server control, be sure it matches the name of the instance you
created in the code-behind file. For example, the ID attribute in the
element below is Name, corresponding to the NameTextBox server control from Step 2.
[C#]
Name:
[Visual Basic]
Name:
5. Include the user control in the Web Forms pages where you want its functionality toappear.
In what order do the events ofan ASPX page Execute?
Control Execution Lifecycle
The server loads an ASP.NET page every time it is requested and then unloads it afterthe request is completed. The page and the server controls it contains are responsible forexecuting the request and rendering HTML back to the client. Although the communicationbetween the client and the server is stateless and disconnected, the client experience mustappear to be that of a continuously executing process.
-
8/9/2019 DotNet Questions and Answers
5/27
This illusion of continuity is created by the ASP.NET page framework and by the pageand its controls. On postback, a control must behave as if it were starting where it left off at theend of the previous Web request. The ASP.NET page framework makes it relatively easy toperform state management, but control developers must be aware of the control executionsequence to achieve the effect of continuity. Control developers need to understand whichinformation is available to a control at each phase in its lifecycle, which data is persisted, andwhat the control's state is when it is rendered. For example, a control is unable to invoke itsparent until the tree of controls on a page has been populated.
The following table provides a high-level overview of the phases in the lifecycle of acontrol. For details, follow the links in the table.
Phase What a control needs to do Method or event to override
Initialize Initialize settings needed during the lifetime
of the incoming Web request.Init event (OnInit method)
Load view state At the end of this phase, the ViewStateproperty of a control is automatically
populated as described in Maintaining Statein a Control. A control can override the
default implementation of the
LoadViewState method to customize staterestoration.
LoadViewState method
Process postback data Process incoming form data and updateproperties accordingly. See Processing
Postback Data.
Note Only controls that process postback
data participate in this phase.
LoadPostData method
(ifIPostBackDataHandlerisimplemented)
Load Perform actions common to all requests,
such as setting up a database query. At thispoint, server controls in the tree are created
and initialized, the state is restored, and
form controls reflect client-side data
Load event
(OnLoad method)
Send postback change
notifications
Raise change events in response to state
changes between the current and previous
postbacks.
Note Only controls that raise postback
change events participate in this phase.
RaisePostDataChangedEvent
method
(ifIPostBackDataHandlerisimplemented)
Handle postback
events
Handle the client-side event that caused the
postback and raise appropriate events on the
serverNote Only controls that process postbackevents participate in this phase.
RaisePostBackEvent method
(ifIPostBackEventHandlerisimplemented)
Prerender Perform any updates before the output isrendered. Any changes made to the state of
the control in the prerender phase can be
saved, while changes made in the renderingphase are lost
PreRender event
(OnPreRendermethod)
-
8/9/2019 DotNet Questions and Answers
6/27
Save state The ViewState property of a control isautomatically persisted to a string object
after this stage. This string object is sent to
the client and back as a hidden variable. For
improving efficiency, a control can override
the SaveViewState method to modify theViewState property.
SaveViewState method
Render Generate output to be rendered to the client. Render method
Dispose Perform any final cleanup before the control
is torn down. References to expensiveresources such as database connections must
be released in this phase.
Dispose method
Unload Perform any final cleanup before the control
is torn down. Control authors generally
perform cleanup in Dispose and do nothandle this event.
UnLoad event (On UnLoadmethod)
Dataset, Repeater and List control Difference?
Type of Control Purpose Features
Table General-purpose,
programmable
table.
Can display any combination of HTML text andcontrols.
Supports a TableCell control that can be set to
display information. Does not use templates fordisplay.
Is not inherently data-bound.
Exposes a model for dynamically creating rows
(TableRow controls) and cells (TableCellcontrols).
Repeater Simple, read-only output
Has no built-in support for selecting or editingitems.
Has no default appearance; you must lay out the
list by creating templates. The list can be
vertical, horizontal, all on one line, or in anyformat you specify.
Has no default paging; all data is displayed in a
single list.
Can define separators between elements using a
template.
Supports custom functionality that can be
applied to items (for example, specifying an
-
8/9/2019 DotNet Questions and Answers
7/27
"Add to shopping cart" button for each item).
DataList List output with
editing
Non-tabular
lists (forexample,
comma-
delimited lists)
Easily
customizable
output
Has a table appearance by default, but can be
configured to show any list output.
Can customize look of list extensively.
Has an auto-format option. WYSIWYG template editing.
Supports styles for custom look of items.
Can define separators between elements using atemplate.
Has editable contents (contents displayed in text
boxes or other controls, based on data type ofbound data).
Supports single selection. Multiple selection
requires custom code.
Supports either horizontal (columns) or vertical
(rows) layout of the data items. Has no default paging; all data is displayed in a
single list.
Supports custom functionality that can be
applied to items (for example, specifying an
"Add to shopping cart" button for each item).
DataGrid Full-featured
list output with
editing
Paged reporting
Has a grid appearance by default.
Can customize look of grid extensively.
Has an auto-format option.
Can specify output using bound columns,
columns of buttons or hyperlinks, and customcolumns created using templates.
Has no separator template. However, the grid
renders in a table, and you can specify table
border size and color.
Supports WYSIWYG template editing. Items support styles for custom look.
Can edit, update, and delete contents.
Supports single selection. Multiple selectionrequires custom code.
Has optional paged output.
Supports sorting.
Supports custom functionality that can beapplied to items (for example, specifying an
"Add to shopping cart" button for each item).
1. What method do you use to explicitly kill a user Session?
Ans : Session.Abandon
-
8/9/2019 DotNet Questions and Answers
8/27
Abandon
The Abandon method destroys all the objects stored in a Session object and releasestheir resources. If you do not call the Abandon method explicitly, the server destroys theseobjects when the session times out.
Syntax Session.Abandon
Remarks
When the Abandon method is called, the current Session object is queued for deletion,but is not actually deleted until all of the script commands on the current page have beenprocessed. This means that you can access variables stored in the Session object on the samepage as the call to Abandon, but not in any subsequent Web pages.
For example, in the following script, the third line prints the value Mary. This is because
the Session object is not destroyed until the server has finished processing the script.
Contents.Remove
The Remove method deletes a specific item from the Session object's Contents collection.
Syntax
Session.Contents.Remove ( Item|Index)
Parameter
Item - The name of the member to remove from the collection.
Index - The index entry for the member to remove from the collection.
Remarks
The Contents.Remove method takes either a string or an integer as an inputparameter. If the input parameter is a string, the method will search the contents collection foran item with that name and remove it. If the input parameter is an integer, the method counts
that number of items from the start of the collection, and removes the corresponding item.
Example
The following example adds and removes a variable called myName to theSession.Contents collection.
-
8/9/2019 DotNet Questions and Answers
9/27
Session.Contents.Remove("myName")%>
Contents.RemoveAll
The RemoveAll method deletes all items that have been added to the Session object's
Contents collection.
Syntax
Session.Contents.RemoveAll ()
Example
The following example removes all items that have been added to the Session.contentscollection:
Difference between HTML control and Web control and Server control?
Html Control: Browser will maintain this code. This is call client control.Web Control: Same as Html Control.
Server control: IIS or Server will maintain this code.
Difference Between Global.asax and web.config file?
Global.asax: This file maintain the events. Suppose you want initialize a variablein a particular event means you can assign. User can declare global variable in
this file.
Web.Config: This file maintain the Security measurement. We can connectdatabase globally. This file is fully XML format.
Difference between Trace and Debug?
Trace: After deployment of our project, admin to trace a error in our project use oftrace=true property. If trace is true admin can see the error in the web page.
Debug:
In ASP.NET we have .aspx file and HTML file which file execute first explain
HTML is execute first. Because HTML is browser side code. But .aspx fileis fully contain server side code and controls. So that one take time tocommunicate in the server.
C#
-
8/9/2019 DotNet Questions and Answers
10/27
what is Boxing and Unboxind. Give Example.
Boxing
Boxing is an implicit conversion of a value type to the type object or to any interface
type implemented by this value type. Boxing a value of a value allocates an object instance andcopies the value into the new object.
Consider the following declaration of a value-type variable:
int i = 123;
The following statement implicitly applies the boxing operation on the variable i:
object o = i;
The result of this statement is creating an object o, on the stack, that references a value of the type
int, on the heap. This value is a copy of the value-type value assigned to the variable i. Thedifference between the two variables, i and o, is illustrated in the following figure.
It also possible, but never needed, to perform the boxing explicitly as in the following example:
int i = 123;object o = (object) i;
Example
This example converts an integer variable i to an object o via boxing. Then the value stored in the
variable i is changed from 123 to 456. The example shows that the object keeps the original copy
of the contents, 123.
// boxing.cs// Boxing an integer variableusing System;class TestBoxing{
public static void Main(){
int i = 123;object o = i; // Implicit boxingi = 456; // Change the contents of i
http://ms-help//MS.VSCC/MS.MSDNVS/csref/html/vcrefvaluetypes.htmhttp://ms-help//MS.VSCC/MS.MSDNVS/csref/html/vcrefvaluetypes.htm -
8/9/2019 DotNet Questions and Answers
11/27
Console.WriteLine("The value-type value = {0}", i);Console.WriteLine("The object-type value = {0}", o);
}}
Output
The value-type value = 456The object-type value = 123
Unboxing
Unboxing is an explicit conversion from the type object to a value type or from an interface type toa value type that implements the interface. An unboxing operation consists of:
Checking the object instance to make sure it is a boxed value of the given value type.
Copying the value from the instance into the value-type variable.
The following statements demonstrate both boxing and unboxing operations:
int i = 123; // A value typeobject box = i; // Boxingint j = (int)box; // Unboxing
The following figure demonstrates the result of the preceding statements.
Unboxing Conversion
For an unboxing conversion to a given value type to succeed at run time, the value of the sourceargument must be a reference to an object that was previously created by boxing a value of thatvalue type. If the source argument is null or a reference to an incompatible object, anInvalidCastException is thrown.
Example
http://ms-help//MS.VSCC/MS.MSDNVS/csref/html/vcrefvaluetypes.htmhttp://ms-help//MS.VSCC/MS.MSDNVS/csref/html/vcrefvaluetypes.htm -
8/9/2019 DotNet Questions and Answers
12/27
The following example demonstrates a case of invalid unboxing, of how incorrect unboxing leads toInvalidCastException. By using try and catch, an error message is displayed when the erroroccurs.
using System;public class UnboxingTest
{ public static void Main(){
int intI = 123;
// Boxingobject o = intI;
// Reference to incompatible object produces InvalidCastExceptiontry{
int intJ = (short) o;Console.WriteLine("Unboxing OK.");
}
catch (InvalidCastException e){
Console.WriteLine("{0} Error: Incorrect unboxing.",e);}
}}
Output
System.InvalidCastExceptionat UnboxingTest.Main() Error: Incorrect unboxing.
If you change the statement:
int intJ = (short) o;
to:
int intJ = (int) o;
the conversion will be performed, and you will get the output Unboxing OK.
What are the fundamental difference between value type and reference type?
C# divides types into two categories - value types and reference types. Most of the basicintrinsic types (e.g. int, char) are value types. Structs are also value types. Referencetypes include classes, interfaces, arrays and strings. The basic idea is straightforward - aninstance of a value type represents the actual data (stored on the stack), whereas aninstance of a reference type represents a pointer or reference to the data (stored on theheap).
-
8/9/2019 DotNet Questions and Answers
13/27
The most confusing aspect of this for C++ developers is that C# has predetermined whichtypes will be represented as values, and which will be represented as references. A C++developer expects to take responsibility for this decision.
For example, in C++ we can do this:
int x1 = 3; // x1 is a value on the stackint *x2 = new int(3) // x2 is a reference to a value on the heap
but in C# there is no control:
int x1 = 3; // x1 is a value on the stackint x2 = new int();
x2 = 3; // x2 is also a value on the stack!
Are C# Destructors the same as C++ Destructors? Example.
No! They look the same but they're very different. First of all, a C# destructor isn't
guaranteed to be called at any particular time. In fact it's not guaranteed to be called at all.Truth be told, a C# destructor is really just a Finalize method in disguise. In particular, it isa Finalize method with a call to the base class Finalize method inserted. So this:
class CTest{
~CTest(){
System.Console.WriteLine( "Bye bye" );}
}
is really this:
class CTest{
protected override void Finalize(){
System.Console.WriteLine( "Bye bye" );base.Finalize();
}}
With the arrival of Beta 2, explicitly overriding Finalize() like this is not allowed -the destructor syntax must be used.
Define Delegates?
A delegate is a class derived from System.Delegate. However the language has a specialsyntax for declaring delegates which means that they don't look like classes. A delegaterepresents a method with a particular signature. An instance of a delegate represents amethod with a particular signature on a particular object (or class in the case of a staticmethod). For example:
using System;
-
8/9/2019 DotNet Questions and Answers
14/27
delegate void Stereotype();
class CAmerican{
public void BePatriotic(){
Console.WriteLine( "... ... God bless America.");}
}
class CBrit{
public void BeXenophobic(){
Console.WriteLine( "Bloody foreigners ... " );}
}
class CApplication{
public static void RevealYourStereotype( Stereotype[] stereotypes ){
foreach( Stereotype s in stereotypes )s();
}
public static void Main(){
CAmerican chuck = new CAmerican();CBrit edward = new CBrit();
// Create our list of sterotypes.Stereotype[] stereotypes = new Stereotype[2];
stereotypes[0] = new Stereotype( chuck.BePatriotic );stereotypes[1] = new Stereotype( edward.BeXenophobic );
// Reveal yourselves!RevealYourStereotype(stereotypes );
}}
This produces the following result:
... ... God bless America.Bloody foreigners ...
Does C# Support a Variable Number of Arguments?
Yes, using theparams keyword. The arguments are specified as a list of arguments of aspecific type, e.g. int. For ultimate flexibility, the type can be object. The standard exampleof a method which uses this approach is System.Console.WriteLine().
How can I process command-line Arguments?
-
8/9/2019 DotNet Questions and Answers
15/27
Like this:
using System;
class CApp{
public static void Main( string[] args ){Console.WriteLine( "You passed the following arguments:" );foreach( string arg in args )
Console.WriteLine( arg );}
}
What is Key Qualifier?
The Key qualifier indicates whether the property is part of the namespace handle. Ifmore than one property has the Key qualifier, then all such properties collectively form the key(a compound key).
Explain Shadowing?
When two programming elements share the same name, one of them can hide that is,shadow the other one. In such a situation, the shadowed element is not available forreference; instead, when your code uses the shared name, the Visual Basic compiler resolves itto the shadowing element.
An element can shadow another element in two different ways. The shadowing elementcan be declared inside a subregion of the region containing the shadowed element, in whichcase the shadowing is accomplished through scope. Or a deriving class can redefine a memberof a base class, in which case the shadowing is done through inheritance.
Public Class BaseClsPublic Z As Integer = 100 ' The element to be shadowed.
End Class
Public Class DervClsInherits BaseClsPublic Shadows Z As String = "*" ' The shadowing element.
End Class
Public Class UseClassesDim BObj As BaseCls = New DervCls() ' DervCls widens to BaseCls.Dim DObj As DervCls = New DervCls() ' Access through derived class.Public Sub ShowZ()
MsgBox("Accessed through base class: " & BObj.Z) ' Outputs 100.MsgBox("Accessed through derived class: " & DObj.Z) ' Outputs "*".
End SubEnd Class
Explain and give an example of Finally?
The finally block is useful for cleaning up any resources allocated in the try block. Controlis always passed to the finally block regardless of how the try block exits.
-
8/9/2019 DotNet Questions and Answers
16/27
In this example, there is one illegal conversion statement that causes an exception. Whenyou run the program, you get a run-time error message, but the finally clause will still be executedand display the output.
// try-finallyusing System;
public class TestTryFinally{public static void Main(){
int i = 123;string s = "Some string";object o = s;
try{
// Illegal conversion; o contains a string not an inti = (int) o;
}
finally{
Console.Write("i = {0}", i);}
}}
Output
The following exception occurs:
System.InvalidCastException
Although an exception was caught, the output statement included in the finally block willstill be executed, that is:
i = 123
For more information on finally, see try-catch-finally.
What is GAC? Define.
Global assembly catch. Gacutil is to view assembly files.
VB.NET and Database
-
8/9/2019 DotNet Questions and Answers
17/27
Overview: VPN?
Using a Virtual Private Network (VPN) is the most secure option for implementing replication over theInternet. VPNs include client software so that computers connect over the Internet (or in special cases,even an intranet) to software in a dedicated computer or a server. Optionally, encryption at both endsas well as user authentication methods keep data safe. The VPN connection over the Internet logically
operates as a Wide Area Network (WAN) link between the sites.
A VPN connects the components of one network over another network. This is achieved by allowing theuser to tunnel through the Internet or another public network (using a protocol such as Microsoft Point-to-Point Tunneling Protocol (PPTP) available with the Microsoft Windows NT version 4.0 orMicrosoft Windows 2000 operating system, or Layer Two Tunneling Protocol (L2TP) available with theWindows 2000 operating system). This process provides the same security and features previouslyavailable only in a private network.
Explain About Two-Tier, Three-Tier and N-Tier System?
Overview: RCW and CCW?
When a .NET client activates a COM object, the runtime generates an instance of the runtime callablewrapper (RCW) to wrap the COM type. As the following illustration shows, the runtime uses metadataobtained from an imported COM type library to generate the RCW. The wrapper marshals dataaccording to the rules established by the interop marshaling service.
-
8/9/2019 DotNet Questions and Answers
18/27
There are two ways to customize an RCW. If you can modify the Interface Definition Language (IDL)source, you can apply type library file (TLB) attributes and import the type library. Alternatively, you canapply interop-specific attributes to imported types and generate a new assembly. Support forcustomizing standard RCWs is limited by these attributes.
To modify the IDL source
1. Apply TLB attributes to libraries, types, members, and parameters. Use the custom
keyword and an attribute value to change metadata. By applying TLB attributes, youcan:
Specify the managed name of an imported COM type, instead of allowing the
import utility to select the name according to standard conversion rules.
Explicitly define a destination namespace for the types in a COM library.
2. Compile the IDL source code.
3. Generate an assembly from the resulting type library file or from a dynamic link libraryfile (DLL) that contains the type you intend to implement.
To modify an imported assembly
1. Import the type library file. Use the Type Library Importer (Tlbimp.exe) to generate an
assembly DLL.2. Create a text file from the imported assembly by using the MSIL Disassembler
(Ildasm.exe).
3. Apply interop attributes to the text file.
4. Generate a new assembly from the modified text file by using the MSIL Assembler(Ilasm.exe).
COM Callable Wrappers
A COM callable wrapper (CCW) exposes .NET Framework objects to COM. By compiling amanaged project into an assembly DLL, you automatically create the metadata required to describeeach type in the assembly. The runtime uses this metadata to generate a CCW whenever a COMclient activates managed object.
To customize a CCW, apply interop-specific attributes to your managed source code andcompile the source into an assembly, as shown in the following illustration. In this example,Tlbexp.exe converts managed types to COM.
-
8/9/2019 DotNet Questions and Answers
19/27
CCW generation and method calls
By applying attributes to your code, you can alter interface and data marshaling behavior withinthe confines of the interop marshaling service. For example, you can control the format of the data
passed as an argument to a method. You can also control which types in an assembly are exposedto COM.
Difference between Typed data set and Untyped data set?
The difference between the two lies in the fact that a Typed DataSet has a schema and
An Untyped DataSet does not have one. It should be noted that the Typed Datasets have more
support in Visual studio. A typed dataset gives us easier access to the contents of the tablethrough strongly typed programming that uses information from the underlying data schema. A
typed DataSet has a reference to an XML schema file:
Dim s As Strings = dsCustomersOrders1.Customers(0).CustomerID
In contrast, if we are working with an untyped DataSet, the equivalent code looks like this:
Dim s As String s = CType ( dsCustomersOrders1.Tables ( "Customers" ). Rows(0). Item
("CustomerID"), String)
As the syntax is much simpler and more practical, using typed Datasets is much more
handy.
Difference between Clustered Index and Non-Clustered index?
Clustered Index - Orders the records in the table based on the primary key. Only
allowed one Clustered Index per table.
Non-Clustered Index - creates a list of presorted pointers to the recors in a table.
Allowed multiple non-clustered indexes per table.
-
8/9/2019 DotNet Questions and Answers
20/27
What is Function, View and Stored procedure in SQL Server 2000?
A view can be thought of as either a virtual table or a stored query. The data accessible througha view is not stored in the database as a distinct object. What is stored in the database is aSELECT statement. The result set of the SELECT statement forms the virtual table returned by theview. A user can use this virtual table by referencing the view name in Transact-SQL statements
the same way a table is referenced. A view is used to do any or all of these functions:
Restrict a user to specific rows in a table.
For example, allow an employee to see only the rows recording his or her work in a labor-tracking table.
Restrict a user to specific columns.
For example, allow employees who do not work in payroll to see the name, office, work
phone, and department columns in an employee table, but do not allow them to see any
columns with salary information or personal information.
Join columns from multiple tables so that they look like a single table.
Aggregate information instead of supplying details.
For example, present the sum of a column, or the maximum or minimum value from a
column.
Views are created by defining the SELECT statement that retrieves the data to be presented by theview. The data tables referenced by the SELECT statement are known as the base tables for the view.In this example, titleview in the pubs database is a view that selects data from three base tables to
present a virtual table of commonly needed data:
CREATE VIEW titleviewASSELECT title, au_ord, au_lname, price, ytd_sales, pub_idFROM authors AS a
JOIN titleauthor AS ta ON (a.au_id = ta.au_id)JOIN titles AS t ON (t.title_id = ta.title_id)
You can then reference titleview in statements in the same way you would reference a table:
SELECT *FROM titleview
A view can reference another view. For example, titleview presents information that is useful formanagers, but a company typically discloses year-to-date figures only in quarterly or annual financialstatements. A view can be built that selects all the titleview columns except au_ord and ytd_sales.This new view can be used by customers to get lists of available books without seeing the financialinformation:
CREATE VIEW Cust_titleviewAS
-
8/9/2019 DotNet Questions and Answers
21/27
SELECT title, au_lname, price, pub_idFROM titleview
Views can be used to partition data across multiple databases or instances of Microsoft SQL Server2000. Partitioned views can be used to distribute database processing across a group of servers. Thegroup of servers has the same performance benefits as a cluster of servers, and can be used to support
the processing needs of the largest Web sites or corporate data centers. An original table is subdividedinto several member tables, each of which has a subset of the rows from the original table. Eachmember table can be placed in databases on separate servers. Each server also gets a partitionedview. The partitioned view uses the Transact-SQL UNION operator to combine the results of selectsagainst all the member tables into a single result set that behaves exactly like a copy of the full originaltable. For example, a table is partitioned across three servers. On the first server you define apartitioned view similar to this:
CREATE VIEW PartitionedView ASSELECT *
FROM MyDatabase.dbo.PartitionTable1UNION ALLSELECT *
FROM Server2.MyDatabase.dbo.PartitionTable2UNION ALLSELECT *
FROM Server3.MyDatabase.dbo.PartitionTable3
You define similar partitioned views on each of the other servers. With these three views, any Transact-SQL statements on any of the three servers that reference PartitionedView will see the same behavioras from the original table. It is as if a copy of the original table exists on each server, when in fact thereis only one member table and a partitioned view on each table. For more information, see Scenarios forUsing Views.
Views in all versions of SQL Server are updatable (can be the target of UPDATE, DELETE, or INSERTstatements), as long as the modification affects only one of the base tables referenced by the view, for
example:
-- Increase the prices for publisher '0736' by 10%.UPDATE titleviewSET price = price * 1.10WHERE pub_id = '0736'GO
SQL Server 2000 supports more complex types of INSERT, UPDATE, and DELETE statements thatreference views. INSTEAD OF triggers can be defined on a view to specify the individual updates thatmust be performed against the base tables to support the INSERT, UPDATE, or DELETE statement.Also, partitioned views support INSERT, UDPATE, and DELETE statements that modify multiplemember tables referenced by the view.
Indexed views are a SQL Server 2000 feature that greatly improves the performance of complex viewsof the type usually found in data warehouses or other decision support systems.
Views are called virtual tables because the result set of a view is us not usually saved in the databaseThe result set for a view is dynamically incorporated into the logic of the statement and the result set isbuilt dynamically at run time.
-
8/9/2019 DotNet Questions and Answers
22/27
Complex queries, such as those in decision support systems, can reference large numbers of rows inbase tables, and aggregate large amounts of information into relatively concise aggregates such assums or averages. SQL Server 2000 supports creating a clustered index on a view that implementssuch a complex query. When the CREATE INDEX statement is executed the result set of the viewSELECT is stored permanently in the database. Future SQL statements that reference the view willhave substantially better response times. Modifications to the base data are automatically reflected inthe view.
The SQL Server 2000 CREATE VIEW statement supports a SCHEMABINDING option thatprevents the tables referenced by the view being changed without adjusting the view. You must
specify SCHEMABINDING for any view on which you create an index.
What is Trigger? Which is new in SQL Server 2000?
Microsoft SQL Server 2000 triggers are a special class of stored procedure defined toexecute automatically when an UPDATE, INSERT, or DELETE statement is issued against a table
or view. Triggers are powerful tools that sites can use to enforce their business rules automaticallywhen data is modified. Triggers can extend the integrity checking logic of SQL Server constraints,defaults, and rules, although constraints and defaults should be used instead whenever theyprovide all the needed functionality.
Tables can have multiple triggers. The CREATE TRIGGER statement can be defined withthe FOR UPDATE, FOR INSERT, or FOR DELETE clauses to target a trigger to a specific class ofdata modification actions. When FOR UPDATE is specified, the IF UPDATE (column_name) clausecan be used to target a trigger to updates affecting a particular column.
Triggers can automate the processing for a company. In an inventory system, updatetriggers can detect when a stock level reaches a reorder point and generate an order to the supplierautomatically. In a database recording the processes in a factory, triggers can e-mail or page
operators when a process exceeds defined safety limits.
The following trigger generates an e-mail whenever a new title is added in the pubsdatabase:
CREATE TRIGGER reminderON titlesFOR INSERTAS EXEC master..xp_sendmail 'MaryM', 'New title, mention in the next report to distributors.'
Triggers contain Transact-SQL statements, much the same as stored procedures. Triggers,like stored procedures, return the result set generated by any SELECT statements in the trigger.Including SELECT statements in triggers, except statements that only fill parameters, is notrecommended. This is because users do not expect to see any result sets returned by an UPDATE,INSERT, or DELETE statement.
sp_helptrigger (T-SQL)
Returns the type or types of triggers defined on the specified table for the current database.
-
8/9/2019 DotNet Questions and Answers
23/27
Syntax
sp_helptrigger [@tabname =] 'table' [,[@triggertype =] 'type']
Arguments
[@tabname =] 'table'Is the name of the table in the current database for which to return trigger information.
table is nvarchar(776), with no default.
[@triggertype =] 'type'
Is the type of trigger to return information about. type is char(6), with a default of NULL,
and can be one of these values.
Value Description
DELETE Returns DELETE trigger information.
INSERT Returns INSERT trigger information.
UPDATE Returns UPDATE trigger information.
Return Code Values
0 (success) or 1 (failure)
Remarks
Column name Data type Description
Trigger_name sysname Name of the trigger
Trigger_owner sysname Name of the trigger owner
Isupdate int 1 = UPDATE trigger
0 = Not an UPDATE trigger
Isdelete int 1 = DELETE trigger
0 = Not a DELETE trigger
Isinsert int 1 = INSERT trigger
0 = Not an INSERT trigger
Permissions
Execute permissions default to the public role.
Examples
-
8/9/2019 DotNet Questions and Answers
24/27
This example creates a trigger named sales_warn that raises error 50010 when the
amount of books sold is 10. Then, sp_helptrigger is executed to produce information about
the trigger(s) on the sales table.
USE pubs
CREATE TRIGGER sales_warn
ON sales
FOR INSERT, UPDATE
AS RAISERROR (50010, 16, 10)
EXEC sp_helptrigger sales
Here is the result set:
trigger_name trigger_owner isupdate isdelete isinsert
------------- ----------------------- ----------- ----------- ---------
sales_warn dbo 1 0 1
(1 row(s) affected
You can use the FOR clause to specify when a trigger is executed:
AFTER
The trigger executes after the statement that triggered it completes. If the statementfails with an error, such as a constraint violation or syntax error, the trigger is not executed.
AFTER triggers cannot be specified for views, they can only be specified for tables. You
can specify multiple AFTER triggers for each triggering action (INSERT, UPDATE, or
DELETE). If you have multiple AFTER triggers for a table, you can use
sp_settriggerorder to define which AFTER trigger fires first and which fires last. Allother AFTER triggers besides the first and last fire in an undefined order which you cannot
control.
AFTER is the default in SQL Server 2000. You could not specify AFTER orINSTEAD OF in SQL Server version 7.0 or earlier, all triggers in those versions operated
as AFTER triggers.
-
8/9/2019 DotNet Questions and Answers
25/27
INSTEAD OF
The trigger executes in place of the triggering action. INSTEAD OF triggers can be
specified on both tables and views. You can define only one INSTEAD OF trigger for eachtriggering action (INSERT, UPDATE, and DELETE). INSTEAD OF triggers can be used
to perform enhance integrity checks on the data values supplied in INSERT and UPDATEstatements. INSTEAD OF triggers also let you specify actions that allow views, which
would normally not support updates, to be updatable.
ALTER TRIGGER
Examples
This example creates a trigger that prints a user-defined message to the client when
a user tries to add or change data in the roysched table. Then, the trigger is alteredusing ALTER TRIGGER to apply the trigger only on INSERT activities. This
trigger is helpful because it reminds the user who updates or inserts rows into this
table to also notify the book authors and publishers.
USE pubs
GO
CREATE TRIGGER royalty_reminder
ON roysched
WITH ENCRYPTION
FOR INSERT, UPDATE
AS RAISERROR (50009, 16, 10)
-- Now, alter the trigger.
USE pubs
GO
ALTER TRIGGER royalty_reminder
ON roysched
FOR INSERT
AS RAISERROR (50009, 16, 10)
-
8/9/2019 DotNet Questions and Answers
26/27
Message 50009 is a user-defined message in sysmessages. For information
about creating user-defined messages, see sp_addmessage.
DROP TRIGGER (T-SQL)Removes one or more triggers from the current database.
Syntax
DROP TRIGGER {trigger} [,...n]
Examples
This example drops the employee_insupd trigger.
USE pubs
IF EXISTS (SELECT name FROM sysobjects
WHERE name = 'employee_insupd' AND type = 'TR')
DROP TRIGGER employee_insupd
GO
Define. char, varchar, text, nvarchar and ntext?
What is patindex and charindex?
Patindex: Returns the string position of the first occurrence of pattern
Ex: Select patindex(%o%, Microsoft)
Ans: 5. Note: % is must
Charindex: Same as patindex but you can specify the string position.
Ex: charindex ( Expression1, Expression2 [ , start_location])
What is Stuff in SQL server 2000?
-
8/9/2019 DotNet Questions and Answers
27/27
Specify length of characters and inserts another set of characters at aspecified starting point.
Stuff(char_exp, start, length, char_exp[ New ] )
Ex: stuff(abcdef, 2, 3 ijklm)
Ans: aijklmdef