Вы находитесь на странице: 1из 46

c 


  
 
  

Consider the following URL:

http:// localhost/form.aspx?param1=career&param2=ride

This html addresses use QueryString property to pass values between pages.

From the URL above the information obtained is:

form.aspx: which is the destination page for your browser.


Param1 is the first parameter, the value of which is set to career
Param2 is the first parameter, the value of which is set to ride

The µ?¶ marks the beginning of the QueryString


µ&¶ is used as a separator between parameters.

private void formButtonSubmit_Click(object sender, System.EventArgs e)


{
Response.Redirect("form.aspx?Param1=" +
this.formTextfieldParam1.Text + "&Param2=" +
this. formTextfieldParam2.Text);
}

The above code is a submit button event handler and it sends the values of the query string to the
second page.

The following code demonstrates how to retrieve these valus on the second page:
private void Page_Load(object sender, System.EventArgs e)
{
this.form2TextField1.Text = Request.QueryString["Param1"];
this. form2TextField2.Text = Request.QueryString["Param2"];
}

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

for (int i =0;i < Request.QueryString.Count;i++)


{
Response.Write(Request.QueryString[i]);
}


 
  


When there is a need to keep the business logic separate from the User Interface or when there is
some class which is big enough to have multiple number of developers implement the methods
in it, the class can be separated and written in different files as partial class.
The keyword partial must appear in each class.

//syntax for C#
Public partial class MyPartialClass1
{
//code
}

// this code could be in file1

Public partial class MyPartialClass1


{
//code
}
// this code could be in file2


  



Ôp If a site happens to not maintain a ViewState, then if a user has entered some information in a
large form with many input fields and the page is refreshes, then the values filled up in the form
are lost.
Ôp he same situation can also occur on submitting the form. If the validations return an error, the
user has to refill the form.
Ôp hus, submitting a form clears up all form values as the site does not maintain any state called
ViewState.
Ôp In ASP .NE, the ViewState of a form is maintained with a built-in state management technique
keeps the state of the controls during subsequent postbacks by a particular user.
Ôp he ViewState indicates the status of the page when submitted to the server. he status is
defined through a hidden field placed on each page with a <form runat="server"> control.
<input type="hidden" name="__VIEWSAE" value="CareerRide">
Ôp he ViewState option can be disabled by including the directive <%@ Page
EnableViewState="false"%> at the top of an .aspx page
Ôp If a ViewState of a certain control has to be disabled, then set EnableViewState="false".

ASP.NET - What is ViewState? Explain its benefits and limitations - May 08, 2009 at 17:40 PM
by Shuchi Gaurip


  

c 



 

Viewstate is used to maintain or retain values on postback. It helps in preserving a page.


Viewstate is internally maintained as a hidden field in encrypted form along with a key.

(
 

i) No server resources.
ii) Viewstate ensures security because it stores the data in encrypted format.
iii) Viewstates are simple. They are used by enabling or disabling the viewstate properties.
iv) It is based on the wish of developer that they want to implement it at the page level or at
control level.

l 
 

i) If large amount of data is stored on the page, then page load might cause a problem.
ii) Does not track across pages. Viewstate information does not automatically transfer from page
to page.

ASP.NET - What is ViewState? - May 20, 2009 at 10:10 AMp


 



Viewstate is the mechanism that automatically saves the values of the page's items just before
rendering the page. It stores items added to a page¶s ViewState property as hidden fields on the
page.


 

 !

A URL (Uniform Resource Locator) is the address of some resource on the Web. A resource is
nothing but a page of a site. There are other type of resources than Web pages, but that's the
easiest conceptually.

A URI is a unique identifier to usually a namespace.


Though it looks like a URL but it doesn¶t have to necessarily locate any resource on the web.

URI is a generic term. URL is a type of URI.

ASP.NET - What is the difference between URL and URI? - June 04, 2009 at 15:00 PM by Shuchi Gaurip

!o Uniform Resource Identifier: it¶s a string and its responsibility is to identify a resource by
metaoinformation. It gives information about only one resource.

 o Uniform Resource Locator: identifies the resource on the net and tells it is obtainable
using what protocols.

l  "#  "# $%"#  &'"

Terms related to lifecycle of a remoting object.

The LeaseTime property protects the object so that the garbage collector does not destroy it as
remoting objects are beyond the scope of the garbage collector. Every object created has a
default leasetime for which it will be activated. Once the leasetime expires, the object is eligible
again for garbage collector and is eventually destroyed. Default value is 5 minutes.
Even though the leasetime of an object has expired, there still may be clients who would still
need the remoting object on the server. In such cases the leasemanager keeps a track of such
clients and asks them if they need the object and are ready to extend or sponsor the object to
extend its existence. This is done through SponsorshipTime property, which is then based on the
sponsor.

The RenewOnCallTime property defines the duration for which a remoting object's lease is
extended if a sponsor is found. The default value is 2 minutes.

The LeaseManager class has a property PollTime, which defines the frequency at which the
LeaseManager polls the leases. Default is 10 seconds.

l%('(c"

Caching technique allows to store/cache page output or application data on the client. The
cached information is used to serve subsequent requests that avoid the overhead of recreating the
same information. This enhances performance when same information is requested many times
by the user.




 %('(c"

Caching in ASP.NET can be of the following types


Page Output Caching
Page Fragment Caching
Data Caching

ASP.NET - types of caching - Dec 25, 2009 at 19:55 PM by Nishant Kumar

c )('(c"

'$

%
This type of caching is implemented by placing OutputCache directive at the top of the .aspx
page at design time.
For example:
<%@OutputCache Duration= "30" VaryByParam= "DepartmentId"%>

The duration parameter specifies for how long the page would be in cache and the VaryByParam
parameter is used to cache different version of the page.
The VaryByParam parameter is useful when we require caching a page based on certain criteria.

'*
%
This technique is used to store part of a Web form response in memory by caching a user control.

l
%
Data Caching is implemented by using Cache object to store and quick retrieval of application
data.
Cache object is just like application object which can be access anywhere in the application.
The lifetime of the cache is equivalent to the lifetime of the application. .

c 
  
('(c"  

Types of sessions:

Ôp InProc: he default way to use sessions. InProc is the fastest way to store and access sessions.
Ôp ÈutProc:
i. State server: 15% slower than InProc. Session is serialized and stored in aspnet_state.exe
process. Stateserver sessions can be stored on a separate machine too.
ii. SQL Server: 25% slower than InProc. Used when data is to be serialized and stored in SQL
Server database.

ASP.NET Session state management options- March 13, 2009 at 15:20 PM by Amit Satputep





  



  

('(c"

!+' 




Ôp he In-Process type of Session state management stores the session in memory on the web
server.
Ôp In order to have a user always reconnect to the same web-server, a sticky server is needed.

$
++' 




Ôp Èut-of-Process Session state management stores data in an external data source.


Ôp he external data source may be a SQL Server or a State Server service.
Ôp Èut-of-Process state management requires the objects in a session to be serializable.





  %) 

(
 

a. They are simple to use.


b. Light in size, thus occupy less memory.
c. Stores server information on client side
d. Data need not to be sent back to server.
e. Cookies persist for much longer period of time than a session.

l 
 

a. Since they are stored on the client side in plain text, they are not secure.
b. Number of cookies that can be stored and their size is limited.
c. They don't work if security level is set too high in browser.
d. Some people might just disable cookies on their browsers.
c 


  


% ''
: It refers to the scenario where on event of some controls posts from one
page to another instead of a normal postback. Normal postback is when for e.g. a button (or any
control that postbacks) is clicked and web page is submits the page back to itself which means a
return trip. In Cross page posting, on click of a button there would be no return trip.

Crossopage posting is done at the control level. It is possible to create a page that posts to
different pages depending on what button the user clicks on. It is handled by done by changing
the postbackurl property of the controls.

c  
  

 
 



PreviousPage property is set to the page property of the nest page to access the viewstate value
of the page in the next page. Page poster = this.PreviousPage;
Once that is done, a control can be found from the previous page and its state can be read.
Label posterLabel = poster.findControl("myLabel");
string lbl = posterLabel.Text;


 , %l('(c"

SQL Cache Dependency in ASP.NET: It is the mechanism where the cache object gets
invalidated when the related data or the related resource is modified. It is a feature in SQL Server
2005 and SQL Server 2000.

3 types of SQLocache dependencies exist:

a. Other cache items.


b. Files/folders.
c. Dependencies on a database query.


   
 
#%*

WCF is a framework that builds applications that can interocommunicate based on service
oriented architecture consuming secure and reliable web services. This also helps in Distributed
computing. The WCF also brings together the various communication models into a single
model.

c 

%*+ #-

#c(l


WCF Service is composed of three components:

Ôp   It implements the service needed.


Ôp -

 is an environment that hosts the developed service.
Ôp c
 are the connection points for the clients to connect to the service. Clients find
the end points through three components like service contract, binding, and address.
l
%* 

WCF can create services similar in concept to ASMX, but has much more capabilities. WCF is
much more efficient than ASP.Net coz it is implemented on pipeline. WCF is more secure,
reliable. As WCF is implemented on a different pipeline it does not have all Http capabilities
(Http session, cache etc


 
.


) 

Script injection attacks called Crossosite scripting (XSS) attacks exploit vulnerabilities in Web
page validation by injecting clientoside script code.

This code executes on the user¶s browser after the browser downloads the script code from a
trusted site and then the browser has no way of determining the legitimacy code.

ASP.NET - What are script injection attacks? - June 04, 2009 at 15:00 PM by Shuchi Gaurip

Script injection attacks occur when an end user tries to fill in malicious code in the form or input
fields of a form to access database or change it or destroy it. The malicious code tries to fool the
application, that it was just another end user. The technique involves submitting contents
wrapped in <script>, <object>, <applet>, <embed>, <frame>, <link> etc tags.

Request validation and validating the input provided by the end user are a solution to such
attacks. One can use the following in the web.config for validating requests for all pages in the
application.

<configuration>
<appSettings/>
<connectionStrings/>
<system.web>
<pages validateRequest="false"/>
</system.web>
</configuration>


 (
/
('(c"

Authorization is a process that takes place based on the authentication of the user. Once
authenticated, based on user¶s credentials, it is determined what rights des a user have. In
ASP.NET, there are two ways to authorize access to a given resource:

a. File authorization
b. URL authorization


 


 * 



Login controls are part of ASP. Net¶s UI controls collection which allows users to enter their
username and password to login to a website/application. They provide login solution without
the need of writing code. They by default work with ASP.Net membership roles and forms
authentication. Forms authentication on the other hand refers to the authentication type being
used by an application. ASP.Net supports Forms Authentication, Integrated windows
authentication and Custom authentication. One can however, change or configure the login
controls to work with the authentication mechanism chosen and not just Forms authentication
which is default.





Overriding o Methods have the same signature as the parent class method.
Overloading o Methods have different parameters list or type or the return type.

l  

Access modifiers are used to control the scope of type members.


There areu pp u  p

p p  p ppupp
 p  p p 
 p 
p 
p 

p 

pp 

p p 

p 
 

l(l$(c"l
 


A Dataset can represent an entire relational database in memory, complete with tables, relations,
and views. A dataset is designed to work without any continuing connection to the original data
source.
You can use For Each loops to move through the data in the dataset.


l
 c  
  


 ('(c"

Delegates provide the functionality behind events.


(p
p pp
 p
pu
p  
 p
pp
p

p pp  
pp
p

p
p
p p p !p
p pup
p
p p  p p
p




  
c 


Init() o when the page is instantiated.


—p"p p
p p pp 
p  p p
 # p"p
p up
pu p
p p p   p
p
p pp$!%—p
&p"p p pu   p 

%
#
 
 (l$(c"

It is dataoaccess technology, p   p 


pp p
p  puu  
pp
pppp
! p 
p
p p  
p
pp'
(
p)
pp
(p
p   p pp
pupp

p  pp
p
p! p p 
pup
p   p *pp
+
pp
+pp
'
# pp
'
(
 pp
p
 p(
 p !p p
p
p   *pp
(,—p'
p   pp
-'p'
p  

p
!p
p
p   p p p p p(
 p !p.//0*pp
-'+p'
p   pp
- p'
p  

l 
0 

A Web application starts with the first request for a resource.


On request, Web forms are instantiated and processed in the server.
Server sends its response to the client.
Application ends once all client sessions end.


 
 

 (


Create a command object.


Set the object¶s CommandText property to the name of the stored procedure.
Set the CommandType property to stored Procedure.
Execute stored procedure using command object¶s method.

l * 




Windows authentication is the default authentication method of the ASP.NET application. It uses
security scheme of windows operating system of corporate network. Windows authentication
uses user names, passwords, and permissions of network resources and Web applications. User
lists for Windows authentication are included in the element of Web.config.
Form authentication allows creating own database of users in the application¶s Web.config file or
in a separate user database and validate the identity of the users when they visit Web site. Users
do not have to be member of a domainobased network to have access to your application.


  )
 1 2  


SSL protects data exchanged between a client and an ASP.NET application by encrypting the
data before it is sent across the internet.

l  
     

Following are the major differences between them:o

" 

Ôp he browser is directly redirected to another page


Ôp here is no round trip
Ôp A Server transfer is possible within a website
Ôp Information can be preserved in Server transfer through a parameter called preserveForm

  

Ôp he browser is requested to redirect to some other page through a message.


Ôp here is a round trip.
Ôp Response redirect is possible within two websites too.
Ôp A state can be maintained in Response redirect but has a lot of drawbacks

l       

Authentication is the process of verifying the identity of a user.

Authorization is process of checking whether the user has access rights to the system.

Authorization is the process of allowing an authenticated user access to resources.

Authentication always proceeds to Authorization.

      

The passing of the control from the child to the parent is called as bubbling. Controls like
DataGrid, Datalist, Repeater, etc can have child controls like Listbox, etc inside them. An event
generated is passed on to the parent as an ItemCommand.

l  


      

ASP.NET runs inside the process of IIS due to which there are two authentication layers which
exist in the system.

First authentication happens at the IIS level and the second at ASP.NET level per the
WEB.CONFIG file.

)

At first, IIS ensures that the incoming request is from an authenticated IP address.
Otherwise the request is rejected.

By default IIS allows anonymous access due to which requests are automatically authenticated.

However, if this is changed, IIS performs its own user authentication too.

ASP.net checks if impersonation is enabled if a request is passed to ASP.net by an authenticated


user. If it is enabled, ASP.net acts itself as an authenticated user else it acts with its own
configured account.
Finally the OS resources are requested by the identity obtained from previous step.
The user is granted the resources if the authentication is successful else the resources are denied.

Resources can include ASP.net page, code access security features to extend authorization step
to disk files, registry keys, etc.

c 
 


  ('(c"

ASP.NET supports 3 authentication mechanisms:

a.  (


 This is used for an intranet based application. Used to authenticate
domain users within a network. By default windows authentication is used.

b. *(


 It¶s a custom security based on roles and user accounts created
specifically for an application.

c. ' 
(


 This is based on hotmail passport account.

     

If windows authentication mode is selected for an ASP.NET application, then authentication also
needs to be configured within IIS since it is provided by IIS.

IIS provides a choice for four different authentication methods:


Anonymous: IIS doesn¶t perform any authentication. All are allowed to access the ASP.NET
application.

Basic: users must provide a windows username and password to connect. This information is
plain text which makes this mode insecure.

Digest: Users need to provide a password which is sent over the network. However in this case
the password is hashed. It also requires that all users be using IE 5 or later versions.

Windows integrated: passwords are not sent over the network. The application uses either the
Kerberos or challenge/response protocols authenticate the user. Users need to be running IE 3.01
or later.

  

Passport authentication provides authentication using Microsoft¶s passport service.


If passport authentication is configured and users login using passport then the authentication
duties are offoloaded to the passport servers.

Passport uses an encrypted cookie mechanism to indicate authenticated users. The passport users
are considered authenticated while the rest are redirected to the passport servers to log in, after
which they are redirected back to the site.
Passport Software Development Kit can be downloaded and installed http://
msdn.microsoft.com/library/default.asp?url=/downloads/list/websrvpass.aps.

ð   

Using form authentication, ones own custom logic can be used for authentication.

ASP.NET checks for the presence of a special session cookie when a user requests a page for the
application. Authentication is assumed if the cookie is present else the user is redirected to a web
form.

     !  


:: pp
p

Ky Nishant Kumar

A web application starts when a browser requests a page of the application first time. The request
is received by the IIS which then starts ASP.NET worker process (aspnet_wp.exe). The worker
process then allocates a process space to the assembly and loads it. An application_start event
occurs followed by Session_start. The request is then processed by the ASP.NET engine and
sends back response in the form of HTML. The user receives the response in the form of page.

The page can be submitted to the server for further processing. The page submitting triggers
postback event that causes the browser to send the page data, also called as view state to the
server. When server receives view state, it creates new instance of the web form. The data is then
restored from the view state to the control of the web form in Page_Init event.

The data in the control is then available in the Page_load event of the web form. The cached
event is then handled and finally the event that caused the postback is processed. The web form
is then destroyed. When the user stops using the application, Session_end event occurs and
session ends. The default session time is 20 minutes. The application ends when no user
accessing the application and this triggers Application_End event. Finally all the resources of the
application are reclaimed by the Garbage collector.

c 
('(c"

Lifecycle of a page in ASP.NET follows following steps:

Page_Init(Initialization of the page) >> LoadViewState(loading of View State) >>


LoadPostData(Postback data processing) >> Page_Load(Loading of page) >>
RaisePostDataChangedEvent(PostBack change notification) >> RaisePostBackEvent (PostBack
event handling) >> Page_PreRender (Page Pre Rendering Phase) >> SaveViewState (View state
saving) >> Page_Render (Page rendering) >> Page_UnLoad (Page unloading)
"  
  


:: pp
p

Ky Nishant Kumar

( +* 

 ('(c"

Ôp Web application exists in compiled form on the server so the execution speed is faster as
compared to the interpreted scripts.
Ôp ASP.NE makes development simpler and easier to maintain with an event-driven, server-side
programming model.
Ôp Keing part of .Framework, it has access to all the features of .Net Framework.
Ôp Content and program logic are separated which reduces the inconveniences of program
maintenance.
Ôp ASP.NE makes for easy deployment. here is no need to register components because the
configuration information is built-in.
Ôp o develop program logic, a developer can choose to write their code in more than 25 .Net
languages including VK.Net, C#, JScript.Net etc.
Ôp Introduction of view state helps in maintaining state of the controls automatically between the
postbacks events.
Ôp (( !puu p 
" p
pu
 p
 p p


p p
 p


p
p
Ôp 
 
p
p('- !
Ôp  
" p pu
 


    


:: pp
p

Ky Nishant Kumar

ASP.NET web form supports many server controls like Button, TextBox etc. Each control has
associated events. There are three types of server control events.

Postback event
Cached event
Validation event

'
)


This event sends the page to server for processing. This causes the page a roundotrip to the
server.

%


This event stores page data that gets processed when page is submit to the server by postback
event.





This event is handled on the page just before the page is posted back to server.

" 

  

First validations Event occurs just before the page is submitted to the server.
Postback Event occurs that cause the page to be submitted to the server.
Page_Init and Page_Load events are handled.
Cached events are handled.
Lastly, the event that caused the postback is processed.


    
   


:: pp
p

Application state variables


Session state variables
Point to be noted about Application and Session state variables

Ky Nishant Kumar

By default, ASP.NET maintains page data between the requests using mechanism called View
state. Every web form has view state property to retain data. The form's view state can retain data
only in that form. So, when you need one form data in other form, you can't rely on view state.
ASP.NET provides state variables in the Application or Session objects that helps in maintaining
state of the form which can be accessed in other form.

(


 

The data stored in these variables is available to all the users i.e. all the active sessions.

 

 

These are available to the single session who has created the variables.

'



(
 

 
These variable can store any type of data.
Maintaining Session state affects performance.
Session state can be turned off at the application and page levels.
Application state variables are available throughout the current process, but not across
processes.

A trigger is a special kind of stored procedure that automatically executes when an event occurs in the
database server. A trigger is really an event handler. SQL Server allows users to create triggers (event
handlers) for 3 types of events:

* DML Event - Èccurs when a DML (Data Manipulation Language) statement: INSER, UPDAE or
DELEE, is executed.
* DDL Event - Èccurs when a DDL (Data Definition Language) statement: CREAE, ALER, or DRÈP, is
executed.
* Logon Event - Èccurs when a user logins to the Server.

here are 3 different types of triggers (event handlers) based on the types of events they are triggered
by:

* DML rigger - Executes in response to a DML event.


* DDL rigger - Executes in response to a DDL event.
* Logon rigger - Executes in response to a logon event.

;  
    

(  

If you need to sort the output from two queries grouped together with a UNION operator, you
need to apply the ORDER BY clause at the group level, not at the subquery level.

Note that SQL Server and MySQL react differently to the ORDER BY clause used in a subquery
of a UNION operator:

* SQL Server will give error if ORDER BY is used inside a subquery of a UNION operator.
* MySQL will ignore the ORDER BY clause inside a subquery of a UNION operator.

The following tutorial exercise shows you how to use ORDER BY clause with UNION operator:
(SELECT * FROM ggl_links WHERE tag = 'DBA'
ORDER BY created)
UNION
(SELECT * FROM ggl_links WHERE tag = 'DEV'
ORDER BY created)
GO
Msg 156, Level 15, State 1, Line 2
Incorrect syntax near the keyword 'ORDER'.
Msg 156, Level 15, State 1, Line 5
Incorrect syntax near the keyword 'ORDER'.

(SELECT * FROM ggl_links WHERE tag = 'DBA')


UNION
(SELECT * FROM ggl_links WHERE tag = 'DEV')
ORDER BY created
GO

;     ! " 

(  

Sometimes you need to round a numeric value into an integer. SQL Server 2005 offers you a
number of ways to do this:

* FLOOR(value) o Returning the largest integer less than or equal to the input value. The
returning data type is the same as the input value.
* CEILLING(value) o Returning the smallest integer greater than or equal to the input value. The
returning data type is the same as the input value.
* ROUND(value, 0, 0) o Returning the integer most close to the input value. The returning data
type is the same as the input value.
* CAST(value AS INT) o Returning the largest integer less than or equal to the input value. The
returning data type is INT.
* CONVERT(INT, value) o Returning the largest integer less than or equal to the input value.
The returning data type is INT.
The tutorial exercise below gives some good examples of converting numeric values to integers:

SELECT FLOOR(1234.5678);

SELECT CEILING(1234.5678);

SELECT ROUND(1234.5678, 0, 0);

SELECT CAST(1234.5678 AS INT);

SELECT CONVERT(INT, 1234.5678);

GO
1234

1235

1235.0000

1234

1234

l' )

Ky Nishant Kumar

'3

Ôp he column or columns of the table whose value uniquely identifies each row in the table is
called primary key.
Ôp sou can define column as primary key using primary key constraint while you create table.
Ôp When you define a column as primary key, a unique index is created which restricts duplicate
data and fast access to data.
Ôp A column defined as primary key doesn͛t allow null value.
Ôp Ky default, clustered index in created with the column having primary key.

 )

Unique key also ensures data uniqueness like primary key.


A column with unique key defined allows null value.
By default, it creates nonoclustered index.

SQL Server Primary key and Unique key - Feb 3, 2009 at 8:10 am by Nishant Kumar

c 

)  )

Ôp Koth are defined to ensure unique row.


Ôp Primary key creates a clustered index on the column by default.
Ôp Unique creates a non-clustered index by default.
Ôp Primary key doesn't allow NULLs, but unique key allows one NULL only.

Sql server - Define Primary and Unique key - Feb 11, 2010 at 11:55 AM by Shuchi Gaurip

l' )
Primary key: Enforces uniqueness of the column they are attached to. It creates a clustered index
on the column and does not allow null values. Every table can have only one primary key.

Unique Key: Enforces uniqueness of the column they are attached to. It creates a non clustered
index on the column and allows only one NULL value.

° p°p
p

p

What are ways to ensure integrity of data?


Explain the types of Data integrity.
What are integrity constraints? Explain their types. i.e. column and table constraints.
Explain the classes of constraints. i.e. Primary key, Unique, Foreign Key and Check
Constraints..............

;  # $ %&  

(  

If you want to query from two tables with a left outer join, you can use the LEFT OUTER JOIN
... ON clause in the FROM clause. The following query returns output with a left outer join from
two tables: ggl_links and ggl_rates. The join condition is that the id in the ggl_links table equals
to the id in the ggl_rates table:

SELECT l.id, l.url, r.comment FROM ggl_links l


LEFT OUTER JOIN ggl_rates r ON l.id = r.id
GO
id url comment
101 www.globalguideline.com The best
102 www.globalguideline.com/html Well done
103 www.globalguideline.com/sql Thumbs up
104 www.google.com NULL
105 www.yahoo.com NULL
106 www.php.net NULL
107 www.mysql.com NULL

Note that a left outer join may return extra rows from the first (left) table that do not satisfy the
join condition. In those extra rows, columns from the second (right) table will be given null
values.

The extra rows returned from the left outer join in this example represents links that have no
rates in the above example.

;  '(  )! 

(  
If you have a query returning many rows of data, and you want to perform another query on
those rows, you can put the first query as a subquery in the FROM clause of the second query. A
subquery used in this way become a temporary table, and you must provide a table alias name for
the subquery as in "SELECT ... FROM (SELECT ...) aliasName". The following statement
shows you how to use a subquery as base table for the main query:

SELECT * FROM (SELECT l.id, l.url, r.comment


FROM ggl_links l LEFT OUTER JOIN ggl_rates r
ON l.id = r.id) WHERE url LIKE '%er%'
GO
Msg 156, Level 15, State 1, Line 3
Incorrect syntax near the keyword 'WHERE'.

SELECT * FROM (SELECT l.id, l.url, r.comment


FROM ggl_links l LEFT OUTER JOIN ggl_rates r
ON l.id = r.id) s WHERE s.url LIKE '%er%'
GO

101 www.globalguideline.com The best

102 www.globalguideline.com/html Well done

103 www.globalguideline.com/xml Thumbs up

107 www.globalguideline.com/sql NULL

The error on the first query is caused by the missing alias name to name output of the subquery
as a temporary table.

l(/
l+(/


Ky Nishant Kumar

(/


Ôp It is the process of organizing data into related table.


Ôp o normalize database, we divide database into tables and establish relationships between the
tables.
Ôp It reduces redundancy. It is done to improve performance of query.


 /

*
(
Entities of the table must have unique identifier or entity key.
(*
All the attributes of the table must depend on the entity key for that entity.
"(*
All attributes that are not part of the key must not depend on any other nonokey attributes.

l+/


The process of adding redundant data to get rid of complex join, in order to optimize database
performance. This is done to speed up database access by moving from higher to lower form of
normalization.

Sql server - Define Normalization and De- Normalization - Feb 11, 2010 at 11:55 AM by Shuchi Gaurip

l(/
l+(/


Normalization is the process of reducing data redundancy and maintains data integrity. This is
performed by creating relationships among tables through primary and foreign keys.
Normalization procedure includes 1NF, 2NF, 3NF, BCNF, and then the data is normalized.

Denomalization on the contrary is the process of adding redundant data to speed up complex
queries involving multiple table JOINS. One might just go to a lower form of Normalization to
achieve Denormalization and better performance. Data is included in one table from another in
order to eliminate the second table which reduces the number of JOINS in a query and thus
achieves performance.

#$
 % " 

'
I am new to SQL Server and want to learn about the JOIN options. What are all of the JOIN
options in SQL Server? What is the significance of each of the options? I am a little confused
on the differences and syntax, can you provide some examples and explanations? Are JOINs
only for SELECT statements?



Joining tables to obtain the needed data for a query, script or stored stored procedure is a key
concept as you learn about SQL Server development. In a nutshell, joins are typically performed
in the FROM clause of a table or view for the SELECT, INSERT...SELECT, SELECT...INTO,
UPDATE and DELETE statements. In previous versions of SQL Server, join logic could also
have been included in the WHERE clause with = (INNER JOIN), *= (LEFT OUTER JOIN), =*
(RIGHT OUTER JOIN), etc. syntax, but the support has been reduced and the best practice in
SQL Server is to use the syntax outlined in the examples below.
Before we jump into code, let's provide some baseline information on the joins options in SQL
Server:

Ôp INNER JOIN o Match rows between the two tables specified in the INNER JOIN
statement based on one or more columns having matching data. Preferably the join is
based on referential integrity enforcing the relationship between the tables to ensure data
integrity.
Vp Just to add a little commentary to the basic definitions above, in general the
INNER JOIN option is considered to be the most common join needed in
applications and/or queries. Although that is the case in some environments, it is
really dependent on the database design, referential integrity and data needed for
the application. As such, please take the time to understand the data being
requested then select the proper join option.
Vp Although most join logic is based on matching values between the two columns
specified, it is possible to also include logic using greater than, less than, not
equals, etc.
Ôp LEFT OUTER JOIN o Based on the two tables specified in the join clause, all data is
returned from the left table. On the right table, the matching data is returned in addition
to NULL values where a record exists in the left table, but not in the right table.
Vp Another item to keep in mind is that the LEFT and RIGHT OUTER JOIN logic is
opposite of one another. So you can change either the order of the tables in the
specific join statement or change the JOIN from left to right or vice versa and get
the same results.
Ôp RIGHT OUTER JOIN o Based on the two tables specified in the join clause, all data is
returned from the right table. On the left table, the matching data is returned in addition
to NULL values where a record exists in the right table but not in the left table.
Ôp Self oJoin o In this circumstance, the same table is specified twice with two different
aliases in order to match the data within the same table.
Ôp CROSS JOIN o Based on the two tables specified in the join clause, a Cartesian product
is created if a WHERE clause does filter the rows. The size of the Cartesian product is
based on multiplying the number of rows from the left table by the number of rows in the
right table. Please heed caution when using a CROSS JOIN.
Ôp FULL JOIN o Based on the two tables specified in the join clause, all data is returned
from both tables regardless of matching data.

Let's walk through examples from the AdventureWorks sample database that is available for
SQL Server to provide examples of each type of join then provide some insight into the usage
and sample result sets.

NNER JON Example

In this example we are joining between the Sales.SalesOrderDetail and Production.Product


tables. The tables are aliased with the following: SOD for Sales.SalesOrderDetail and P for
Production.Product. The JOIN logic is based on matching records in the SOD.ProductID and
P.ProductID columns. The records are filtered by only returning records with the SOD.UnitPrice
greater than 1000. Finally, the result set is returned in order with the most expensive first based
on the ORDER BY clause and only the highest 100 products based on the TOP clause.

R 
 V



V 

 

  
!V"
 R

 R
 V 
 

#$
 V%
&'! %  % 

% 
'(
V V
V 
 
V )
V 
*' R
+
'',- R
 


LEFT OUTER JON Example

In this example we are combining two concepts to show that more than two tables can be
JOINed in one SELECT statement and more than one JOIN type can be used in a single
SELECT statement. In the sample code below, we are retrieving the matching data between the
Person.Contact and Sales.SalesPerson tables in conjunction with all of the data from the
Sales.SalesPerson table and matching data in the Sales.SalesTerritory table. For records that
exist Sales.SalesPerson table and not in the Sales.SalesTerritory table, NULL values are returned
for the columns in the Sales.SalesTerritory. In addition, this code uses two columns to order the
data i.e. ST.TerritoryID and C.LastName.

R 
 V


V
&

 
  % 
V
 V V
  % -
  %  -

 ,V 
 

V
$
 
 .
V /0
  % -
&'!
VV
'( %  % 
V 
V)  % 
V
&R'( %  % 

V
$ 
 

V
$) 

V
$
'',- 

V
$ 


R T OUTER JON Example

In an effort to explain how the RIGHT OUTER JOIN and LEFT OUTER JOIN is logically a
reciprocal on one another, the code below is reowritten version of the LEFT OUTER JOIN
above. As you can see the JOIN order and tables are different, but the final result set matches
the LEFT OUTER JOIN logic. In the sample code below, we are retrieving the matching data
between the Person.Contact and Sales.SalesPerson tables in conjunction with all of the data from
the Sales.SalesPerson table and matching data in the Sales.SalesTerritory table. For records that
exist Sales.SalesPerson table and not in the Sales.SalesTerritory table, NULL values are returned
for the columns in the Sales.SalesTerritory.

R 
 V


V
&

 
  % 
V
 V V
  % -
  %  -

 ,V 
 

V
$
  .
V /0
  % -
&'! %  % 

V
$ 
'*R'( %  % 
V 
 

V
$) 

V
$
'(
VV
V)  % 
V
'',- 

V
$ 


Self Join Example


In this example, we are actually self joining to the HumanResources.Employee table. We are
doing this to obtain the information about the Employee and Manager relationship in the
HumanResources.Employee table. In conjunction with that JOIN logic we are also joining to the
Person.Contact twice in order to capture the name and title data based on the original Employee
and Manager relationships. In addition, another new concept introduced in this query is aliasing
each of the columns. Although we could have done so in the previous examples, we made point
of doing so in this query to differentiate between the Employee and Manager related data.

R 
 V


!!1
 2!1
2
!V 2!1
V2
!&
 2!1
&
2
!  2!1
 2
!% 2!1
%2
/%V$ 2/%V$2
V 2/%V$V2
&
 2/%V$&
2
  2/%V$ 2
% 2/%V$%2
&'!* ' V
 /%V$
'(* ' V
 /%V$!
!1
)!!1

'(
VV
V)V
'(
VV!
!V)!V
'',-! 


@ROSS JON Example

As indicated above, please heed caution when running or modifying this query in any SQL
Server database environment. The result set is intentionally limited by the TOP 100 clause and
the WHERE clause to prevent a Cartesian product, which is the result of each of the rows from
the left table multiplied by the number of rows in the right table.

R 
 V



V 

 

  
!V"
 R

 R
 V 
 

#$
 V%
&'! %  % 

% 
' (
V V
V 
*' R
+34
'',- R
 


FULL OUTER JON Example

In our last example, we have modified the logic from the LEFT OUTER JOIN example above
and converted the LEFT OUTER JOIN syntax to a FULL OUTER JOIN. In this circumstance,
the result set is the same as the LEFT OUTER JOIN where we are returning all of the data
between both tables and data not available in the Sales.SalesTerritory is returned as NULL.

R 
 V


V
&

 
  % 
V
 V V
  % -
  %  -

 ,V 
 

V
$
 
 .
V /0
  % -
&'!
VV
'( %  % 
V 
V)  % 
V
&RR'( %  % 

V
$ 
 

V
$) 

V
$
'',- 

V
$ 


(



Ôp As you begin to start coding in SQL Server be sure to have a firm understanding of the
JOIN options available as well as the associated data that is retrieved. Be sure to select
the correct JOIN logic based on the data that needs to be retrieved.
Ôp Once you have a firm grasp of the JOIN logic with SELECT statements, progress to
using the logic with INSERT...SELECT, SELECT...INTO, UPDATE and DELETE
statements
Ôp Joins in SQL Server 2005
Ôp In this article, we are going to discuss SQL Server Joins.
Ôp A join is used to combine columns from two or more tables into a single result set. o
join data from two tables you write the names of two tables in the FRÈM clause along
with JÈIN keyword and an ÈN phrase that specifies the join condition. he join
condition indicates how two tables should be compared. In most cases they are
compares on the base on the relationship of primary key of the first table and foreign
key of the second table. In this article I will tell you about three important joins.
Ôp ˜ & 
Ôp r & 
Ôp I have two tables - Vendor table and Advance table. his is how my database tables and
data looks like. I will be using these tables in my samples below.
Ôp * '!+

Ôp
Ôp Figure 1.
Ôp (*'!+
Ôp
Ôp Figure 2.
Ôp Now we are going to apply joins on these tables and see the data results.
Ôp
Ôp   
Ôp An inner join requires each record in the two joined tables to have a matching record.
An inner join essentially combines the records from two tables (A and K) based on a
given join-predicate. he result of the join can be defined as the outcome of first taking
the Cartesian product (or cross-join) of all records in the tables (combining every record
in table A with every record in table K) - then return all records which satisfy the join
predicate. Actual SQL implementations will normally use other approaches where
possible, since computing the Cartesian product is not very efficient. his type of join
occurs most commonly in applications, and represents the default join-type.
Ôp Example: his is explicit inner join:
Ôp R 5V

Ôp 
Ôp 5V
5V
&5V

V$%$
Ôp &'!6V5V
 
Ôp '( 
Ôp 5V
)5V

Ôp *'5V
7)4
Ôp 
Ôp
Ôp Èutput:
Ôp
Ôp Figure 3.
Ôp Example: his is implicit inner join:
Ôp R 5V

Ôp 
Ôp 8&'!5V

Ôp *'5V
5V
)5V
5V
5V
7)4
Ôp 
Ôp Èutput:

Ôp
Ôp Figure 4.
Ôp     
Ôp ˜ 
( ,& 
Ôp An equi-join, also known as an equijoin, is a specific type of comparator-based join, or
theta join that uses only equality comparisons in the join-predicate. Using other
comparison operators (such as <) disqualifies a join as an equi-join. he query shown
above has already provided an example of an equi-join:
Ôp Example:
Ôp R 5V

Ôp 
Ôp 8&'!5V
'(
Ôp 5V
5V
)5V

Ôp 
Ôp r !& 
Ôp A natural join offers a further specialization of equi-joins. he join predicate arises
implicitly by comparing all columns in both tables that have the same column-name in
the joined tables. he resulting joined table contains only one column for each pair of
equally-named columns.
Ôp Example:
Ôp R 5V

Ôp 
Ôp 8&'!5V
R'(
Ôp 
Ôp  & 
Ôp A cross join, Cartesian join or product provides the foundation upon which all types of
inner joins operate. A cross join returns the Cartesian product of the sets of records
from the two joined tables. hus, it equates to an inner join where the join-condition
always evaluates to rue or join-condition is absent in statement.
Ôp Example:
Ôp R 5V

Ôp 
Ôp 8&'!5V
' (
Ôp 
Ôp R 5V

Ôp 
Ôp 8&'!5V

Ôp 
Ôp
Ôp È  
Ôp An outer join retrieves all rows that satisfy the join condition plus unmatched rows in
one or both tables. In most cases you use the equal operator to retrieve rows with
matching columns. However you can also use any of the other comparison operators.
When row with unmatched columns is retrieved any columns from the other table that
are included in the result are given null values.
Ôp Note1: he ÈUER keyword is optional and typically omitted
Ôp Note2: sou can also code left outer joins and right outer joins using the implicit syntax.
Ôp hree types of outer joins.
Ôp ˜ %& 
Ôp he result of a left outer join (or simply left join) for tables A and K always contains all
records of the "left" table (A), even if the join-condition does not find any matching
record in the "right" table (K). his means that if the ÈN clause matches 0 (zero) records
in K, the join will still return a row in the result but with NULL in each column from K.
his means that a left outer join returns all the values from the left table, plus matched
values from the right table (or NULL in case of no matching join predicate).
Ôp Example:
Ôp R 5V

Ôp 
Ôp 5V
&5V
5V
5V

Ôp &'!5V
&(
Ôp 5V
5V
)5V

Ôp 
Ôp Èutput:
Ôp
Ôp Figure 5.
Ôp
Ôp r  "& 
Ôp A right outer join (or right join) closely resembles a left outer join, except with the tables
reversed. Every record from the "right" table (K) will appear in the joined table at least
once. If no matching row from the "left" table (A) exists, NULL will appear in columns
from A for those records that have no match in A.
Ôp Example :
Ôp R 5V

Ôp 
Ôp 5V
&5V
5V

Ôp &'!5V
'*(
Ôp 5V
5V
)5V

Ôp 
Ôp
Ôp )!! - 
Ôp A full outer join combines the results of both left and right outer joins. he joined table
will contain all records from both tables, and fill in NULLs for missing matches on either
side.
Ôp Example:
Ôp R 5V

Ôp 
Ôp 8&'!5V
&RR'(
Ôp 5V
5V
)5V

Ôp 
Ôp È  
Ôp
Ôp ð 

;   ""% 


!$

he trigger, dml_message, provided in previous tutorials was defined to handle all 3 types of DML
statements, INSER, UPDAE, and DELEE.

If you do not want the trigger to handle all 3 types of DML statements, you can list only 1 or 2 of the
statement keywords. For example, the following SQL script defines a trigger that only handle the INSER
statement events:

USE GlobalGuideLineDatabase

CREAE RIGGER new_user ÈN ggl_users


AFER INSER
AS
PRIN 'ime: '+CÈNVER(VARCHAR(12),GEDAE())
+ ' New users added.';

INSER INÈ ggl_users (name) VALUES ('Marc MHI');



ime: Jul 1 2007
Records are inserted, updated, or deleted in ggl_users
ime: Jul 1 2007 New users added.
(1 row(s) affected)
;  .
(
 
#  
/  " 

(  

If you want to know how an existing view was created, you can use SQL Server Management
Studio to automatically generate a "CREATE VIEW" script The following tutorial shows you
how to do this:

1. Run SQL Server Management Studio and connect to SQL server.

2. On the Object Explorer window, follow the object tree: Databases >
GlobalGuideLineDatabasee > Views > dbo.ggl_links_top.

3. Click right mouse button on dbo.ggl_links_top. The context menu shows up.

4. Select "Script Table as" > "CREATE to" > "New Query Editor Window". The following script
will be displayed:

USE [GlobalGuideLineDatabasee]
GO

/****** Object: View [dbo].[ggl_links_top]

Script Date: 05/19/2007 15:07:27 ******/

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

CREATE VIEW [dbo].[ggl_links_top] AS

SELECT id, counts, url FROM ggl_links

WHERE counts > 100;


 
 
+, l 

 

Data Definition Language (DDL)


Data Control Language (DCL)
Data Manipulation Language (DML)
Ky Nishant Kumar

" " 
+, 
SQL Server Provides three types of TransactoSQL statements namely DDL, DCL, and DML.


p 
p  p p

It allows creating, altering and dropping database objects.



p
p  p p

It is used to control access to data in the database.


It controls permission on the database objects using grant, revoke or deny statement.


p 
p  p p

It involves retrieval, insertion, deletion, modification in the database.


It includes select, insert, update, and delete command.

Sql server - What is transact-SQL? Describe its types? - Feb 11, 2010 at 11:55 AM by Shuchi Gaurip


 
 
+, l 

 

ToSQL is used by any application trying to access/use SQL Server. All applications thus interact
with an SQL Server instance using ToSQL statements.

Types of ToSQL:

Ôp Data types
Ôp User defined temporary objects
Ôp Specialized functions global variables
Ôp System and extended procedures
Ôp Cursors

;  &  '!  "!$ 

(  

Two tables can be joined together in a query in 4 ways:

* Inner Join: Returns only rows from both tables that satisfy the join condition.
* Left Outer Join: Returns rows from both tables that satisfy the join condition, and the rest of
rows from the first (left) table.
* Right Outer Join: Returns rows from both tables that satisfy the join condition, and the rest of
rows from the second (right) table.
* Full Outer Join: Returns rows from both tables that satisfy the join condition, the rest of rows
from the first (left) table, and the rest of rows from the second (right) table.




, 

+
 
pu p
p
p 

p
p
p
pp 

ppup
p
pu p
pp-!p
&——p+$ +1p&,& p#%(#2p1 2p-# 3p1 2p p
p
pup
 
pu p p(,—p( 

! ! ! * .0 ! 

(  

If you want to break your output into smaller groups, you can specify multiple column names or
expressions in the GROUP BY clause. Output in each group must satisfy a specific combination
of the expressions listed in the GROUP BY clause. The more columns or expressions entered in
the GROUP BY clause, the smaller the groups will be. The tutorial exercise below shows you
how to break data into groups per "tag" and per year when they were created. Then the group
function COUNT(*) is applied on each group:

SELECT tag, YEAR(created), COUNT(*)


FROM ggl_links GROUP BY tag, YEAR(created)
GO

tag year(created) count(*)

SQA 2003 1

DEV 2004 1

DBA 2005 1

DBA 2006 1

DEV 2006 1

DBA 2007 1

SQA 2007 1

So there is only one row in each group.

   

p p
p  
pup
 p  p
  pp
 p

p( !p-+-&!p-pp
  p

p4 p
p  p  
p) p
$   pp  5p
p p
ppup  pp
   p



 ) 
 )

Ë p
p p p  ppppp pup
p


p
p4 pppp
p
 6p p  p
pp
p u 
 pu p
p
 p
p p
ppppup
p p p p
  
p(,—p
(  p

ppp
  
pp 6p p

(p p pp  ppp 4


pu pp pp p  
 p ppp pup  p  p
p p 
 u (p pp p p p

p  5pp
p p pu  pp
p


p
p
p u 



   , 

+  pp " " p  pup


p 

p

! pup  *p(

p'  p  " p1 
" p
 p
p pu
 pp pu p
p  p
p 
p pp
 p 
p
+  p pp
 pp
 p 4 p p  pp
   p
 

l

+
 


p
 pp"
p

 p! puppupp
 p p p
p
p
p  ppuppupp"

 p p p  
 p
p
pËpp p pp
 p p pp
p
ppp p p"

 p p pp
p  p
p p
p
p p
p p
p  pup
 p p p
p
p
ppup
"
 p


(l$(c" 

ADO.NET is design to provide data access. ADO.NET supports disconnected database access
model which means that connection is open long enough to perform data operation and is closed.
When data is requested by the application, connection is opened, required data is loaded to the
application and connection gets close. So in ADO.NET, connection is only available when it is
required. This model reduces system resource usage and thus enhances performance.

ADO.NET is shipped with the Microsoft .NET Framework. It is used to access relational data
sources, XML, and application data.
ADO.NET uses XML for data transaction between client application and database.

To access data using ADO.NET's DataAdapter objects


p
pp
p
pp

Ôp Create Dataset object using DataAdapter object.


Ôp Load data into Dataset using fill method of DataAdapter.
Ôp Display Data using Dataset object.
Ôp Close connection
(l$(c" (l$

Ôp ADO.NET is considered as evolution version of ADO.


Ôp ADO.NET works with both connected as well as disconnected fashion whereas ADO
works with connected architecture.
Ôp ADO.NET provides disconnected access through DataSet while ADO provides
disconnected access using recordset.
Ôp ADO.NET use XML to transfer data between objects while ADO use binary format to
transfer data.
Ôp ADO.NET is shipped with .Net Framework and implemented using .Net methodology
whereas ADO relies o

(l$(c"l
(



( p pp p

The Physical Data Store


This can be any database, XML files or OLE.

The DataSet
The dataset stores relevant portion of the database on the local machine. It allows data to be
loaded in the memory of the machine and is disconnected from the database. The dataset can
manipulate disconnected data in the memory. It contains one or more DataTable objects. The
DataTable objects contain DataColumns, DataRows and Constraint collections. The DataSet
contains a DataRelations collection which allow you to create associations between rows in one
table and rows in another table.

The Data Provider


A data provider provides a set of components that helps to extract data from database. The
components are as follows:
Connection object
Command object
DataReader
DataAdapter

The Dataview
This determines presentation of a table in the dataset. This is mainly used to sort or filter data in
the dataset.

%

 (l$(c"

"%
$.

The Connection object represents the connection to the database. The Connection object has
ConnectionString property that contains all the information, required to connect to the database.
"%$.

The command object is used to execute stored procedures and command on the database. It
contains methods to execute command on the database such as ExecuteNonQuery, ExecuteScalar
and ExecuteReader.

c 

Executes commands that return no records, such as INSERT, UPDATE, or DELETE
c   
Returns a single value from a database query
c  
Returns a result set by way of a DataReader object

"l
$.

The DataReader object provides a connected, forwardoonly and readoonly recordset from a
database. The Command.ExecuteReader method creates and returns a DataReader object. Since
it is connected to the database throughout its lifetime, it requires exclusive use of connection
object.

"l
(
$.

The DataAdapter object acts a communication bridge between the database and a dataset. It fills
the dataset with data from the database. The dataset stores the data in the memory and it allows
changes. The DataAdapter's update method can transmit the changes to the database.

The DataAdapter Object's properties.


%
Contains the command text or object that selects the data from the database.

! 
%
Contains the command text or object that inserts a row into a table.

l
%
Contains the command text or object that deletes a row from a table.


%
Contains the command text or object that updates the values of a database.

l
 

 (l$(c"

You have connected data access through the DataReader objects of data provider. This object
requires exclusive use of the connection object. It can provide fast and forwardoonly data access.
It doesn't allow editing. Disconnected data access is achieved through the DataAdapter object.
This object establishes connection, executes the command, load data in the DataSet. The dataset
works independent of database. It contains data in the memory and can edit the data. The
changes in the data can be transmitted to the database using Update method of DataAdapter
object.
ll
 
(l$(c"

A DataView object allows you work with data of DataTable of DataSet object. It is associated
with a DataTable and sits on the top of DataTable. It is used to filter and sort data. Data sorting is
accomplished by setting the Sort property and data filter by setting the RowFilter property.



  


(l$(c"

There are two ways to create connection supported by ADO.NET.


Steps to create connection in code
Create instance of connection object.
Set the ConnectionString property.

Steps to create connection using designer


Drag connection object from the Data tab of the toolbox.
Set the ConnectionString property using properties window.

( 
 
 
 (l$(c"

Steps to connect to database

Declare and initialize database connection object with appropriate connection string.
Create a DataAdapter and a Dataset object.
Using fill method of the DataAdapter object, load the data into the Dataset Object.
Display the data using data binding feature of controls like Datagrid or Datalist.

Code to connect to database using VB.NET

Dim m_adptEmp As SqlDataAdapter

Private Sub Page_Load(ByVal sender As System.Object, _


ByValeAsSystem.EventArgs)HandlesMyBase.Load<BR> DimEmpConnAsNewSqlConnecti
on_<BR> ("server=(local);database=Employees;Trusted_Connection=yes")
m_adptEmp = New SqlDataAdapter("select * from Emp", EmpConn)
Dim dsEmp As New DataSet
m_adptEmp.Fill(dsEmp, "Emp")
DataGrid1.DataSource = dsEmp.Tables("Emp").DefaultView
DataGrid1.DataBind()
End Sub

(l$(c"%  l
 

 

 

Declare and initialize database connection object with appropriate connection string.
Create a DataAdapter and a Dataset object.
Using fill method of the DataAdapter object, load the data into the Dataset Object.
Change the adapter's SELECT command.
Create the EmpDetail table.
Add both tables to a single dataset.
Display the data using data binding feature of controls like Datagrid or Datalist.

Dim m_adptEmp As SqlDataAdapter

Private Sub Page_Load(ByVal sender As System.Object, _


ByValeAsSystem.EventArgs)HandlesMyBase.Load<BR> DimEmpConnAsNewSqlConnecti
on_<BR> ("server=(local);database=Employees;Trusted_Connection=yes")
m_adptEmp = New SqlDataAdapter("select * from Emp", EmpConn)
Dim dsEmp As New DataSet
m_adptEmp.Fill(dsEmp, "Emp")
adptEmp.SelectCommand.CommandText = "SELECT * FROM EmpDetail"
Dim EmpDetail As New DataTable("EmpDetail")
adptDB.Fill(EmpDetail)
dsBoth.Tables.Add(Emp)
dsBoth.Tables.Add(EmpDetail)
DataGrid1.DataSource = dsEmp.Tables("Emp").DefaultView
DataGrid1.DataBind()
End Sub

(l$(c"% 

 

Code showing how to fetch data using Stored Procedure.

Imports System
Imports System.Data
Imports System.Data.SqlClient

Private Function FillForm()


Dim myConn As New SqlConnection()
Dim Parm As New SqlParameter()
Dim dr As SqlDataReader
myConn.ConnectionString = "data source=(local);initial catalog=Jobs;integrated security _
=SSPI;persist security info=False;workstation id=XYZ;packet size=4096"
myConn.Open()
Dim cmd As SqlCommand = New SqlCommand("Select_Employer", myConn)
cmd.CommandType = CommandType.StoredProcedure
Parm = cmd.Parameters.Add("@EmployerId", SqlDbType.Int, 9)
Parm.Value = 1
dr = cmd.ExecuteReader()
If (dr.Read = True) Then
txtName.Text = dr("UserName")
end if
dr.Close()
dr = Nothing
cmd.Connection.Close()
myConn.Close()
End Function

l   

l
 

DataSet object can contain multiple rowsets from the same data source as well as from the
relationships between them

Dataset is a disconnected architecture

Dataset can persist data.

l


DataReader provides forwardoonly and readoonly access to data.

Datareader is connected architecture

Datareader can not persist data.

Dataset and datareader in ADO.NET - June 06, 2009 at 10:00 AM by Shuchi Gaurip

l

 



l
 

a. Disconnected
b. Can traverse data in any order front, back.
c. Data can be manipulated within the dataset.
d. More expensive than datareader as it stores multiple rows at the same time.

l


a. Connection needs to be maintained all the time


b. Can traverse only forward.
c. It is read only therefore, data cannot be manipulated.
d. It is less costly because it stores one row at a time

@ &'   

The command objects are used to connect to the Datareader or dataset objects with the help of
the following methods:
c 
(, 

This method executes the command defined in the CommandText property.


The connection used is defined in the Connection property for a query.
It returns an Integer indicating the number of rows affected by the query.

c 


This method executes the command defined in the CommandText property.


The connection used is defined in the Connection property.
It returns a reader object that is connected to the resulting rowset within the database, allowing
the rows to be retrieved.

c 


This method executes the command defined in the CommandText property.


The connection used is defined in the Connection property.
It returns a single value which is the first column of the first row of the resulting rowset.
The rows of the rest of the result are discarded.
It is fast and efficient in cases where a singleton value is required.

@ommand objects in ADO.NET - June 06, 2009 at 10:00 AM by Shuchi Gaurip

%.
  #   

 

Command objects are used to execute the queries, procedures. Sql statements etc. It can execute
stored procedures or queries that use parameters as well.

It works on the basis of certain properties like ActiveConnection, CommandText,


CommandType, Name etc.

Command object has three methods:

a) Execute: executes the queries, stored procedures etc.


b) Cancel: stops the method execution
c) CreateParameter: to create a parameter object

"  

The data adapter objects connect a command objects to a Dataset object.


They provide the means for the exchange of data between the data store and the tables in the
DataSet.

An OleDbDataAdapter object is used with an OLEoDB provider


A SqlDataAdapter object uses Tabular Data Services with MS SQL Server.
Use of data adapter in ADO.NET - June 06, 2009 at 10:00 AM by Shuchi Gaurip

c 
 



Data adapters are the medium of communication between datasource like database and dataset. It
allows activities like reading data, updating data.

  l

The most commonly used methods of the DataAdapter are:

*

This method executes the SelectCommand to fill the DataSet object with data from the data
source.
Depending on whether there is a primary key in the DataSet, the µfill¶ can also be used to update
an existing table in a DataSet with changes made to the data in the original datasource.

*

This method executes the SelectCommand to extract the schema of a table from the data source.
It creates an empty table in the DataSet object with all the corresponding constraints.




This method executes the InsertCommand, UpdateCommand, or DeleteCommand to update the


original data source with the changes made to the content of the DataSet.

Methods of Dataadapter in ADO.NET - June 06, 2009 at 10:30 AM by Shuchi Gaurip

c 
 
 l



Some basic methods of dataadpater are:

a. Fill: adds or updates the rows to dataset from the datasource


b. FillSchema: adds a datatable with the sameschema as in the datasource
c. Update: it calls insert, update, delete sql commands for transferring all the changes from the
dataset to the datasource
d. Dispose : releases all the resources

 l&"   & l 

The DataSet object is a disconnected storage.


It is used for manipulation of relational data.
The DataSet is filled with data from the store
We fill it with data fetched from the data store. Once the work is done with the dataset,
connection is reestablished and the changes are reflected back into the store.

Dataset has a collection of Tables which has DataTable collection which further has DataRow
DataColumn objects collections.
It also has collections for the primary keys, constraints, and default values called as constraint
collection.
A DefaultView object for each table is used to create a DataView object based on the table, so
that the data can be searched, filtered or otherwise manipulated while displaying the data.

Dataset object in ADO.NET - June 06, 2009 at 10:00 AM by Shuchi Gaurip

 l&"   & l 

The DataSet object represents imported or linked data from an application e.g. manually created
Pushpins etc. This object is invalidated once the application is closed. Dataset contains another
collection known as DataTable object. Each DataTable contains a collection of DataRow objects
and each DataRow is a collection of DataColumn objects.

˜ #  (0 1#') 

( Some of the Features are:

. Ability to Set Metatags.


. More control over view state.
. Added and Updated browser definition files.
. ASP.Net Routing.
. he ability to Persist Selected rows in data Control.
. More control over rendered HML in FormView and ListView Controls.
. Filtering Support for datasource Controls.

r #    % "% !* * $   (0 1 

(. Machine.Config file is found in the "CÈNFIG" subfolder of your .NE Framework install directory
(c:\WINN\Microsoft.NE\Framework\{Version Number}\CÈNFIG on Windows 2000 installations). It
contains configuration settings for machine-wide assembly binding, built-in remoting channels, and
ASP.NE.

In .the NE Framework 4.0, the major configuration elements(that use to be in web.config) have been
moved to the machine.config file, and the applications now inherit these settings. his allows the
Web.config file in ASP.NE 4 applications either to be empty or to contain just the following lines.
 # * 0 (0 1 
(. In earlier Versions of .Net, Response.Redirect was used, which issues an HP 302 Found or
temporary redirect response to the browser (meaning that asked resource is temporarily moved to
other location) which inturn results in an extra HP round trip. ASP.NE 4.0 however, adds a new
RedirectPermanent that Performs a permanent redirection from the requested URL to the specified
URL. and returns 301 Moved Permanently responses.
e.g. RedirectPermanent("/newpath/foroldcontent.aspx");

 ;  !!$  %$  %% 2$ !   " "

( In Asp.Net 4 a new element "targetFramework" of compilation tag (in Web.config file) lets you
specify the framework version in the webconfig file as

<?xml version="1.0"?>
<configuration>
<system.web>
<compilation targetFramework="4.0" />
</system.web>
</configuration>

It only lets you target the .NE Framework 4.0 and later verisons.

1 #    %(-/ '$ 



( Microsoft Ajax Library is a client-only JavaScript library that is compatible with all modern browsers,
including Internet Explorer, Google Chrome, Apple Safari, and Mozilla Firefox.Kecause the Microsoft
Ajax Library is a client-only JavaScript library, you can use the library with both ASP.NE Web Forms and
ASP.NE MVC applications. sou can also create Ajax pages that consist only of HML.

3 #" 2 / **     !

( In ASP.NE 4, the CheckKoxList and RadioKuttonList controls support two new values for the
RepeatLayout property, ÈrderedList(he content is rendered as li elements within an ol element) and
UnorderedList(he content is rendered as li elements within a ul element.)

4 #(!  #, *!



( We can set-up a Warm-Up module for warming up your applications before they serve their first
request.Instead of writing custom code, you specify the URLs of resources to execute before the Web
application accepts requests from the network. his warm-up occurs during startup of the IIS service (if
you configured the IIS application pool as AlwaysRunning) and when an IIS worker process recycles.
During recycle, the old IIS worker process continues to execute requests until the newly spawned
worker process is fully warmed up, so that applications experience no interruptions or other issues due
to unprimed caches.

    

The DataSet object is a disconnected storage.


It is used for manipulation of relational data.
The DataSet is filled with data from the store
We fill it with data fetched from the data store. Once the work is done with the dataset,
connection is reestablished and the changes are reflected back into the store.

Steps to fill a dataset in ADO.NET - June 06, 2009 at 10:00 AM by Shuchi Gaurip

    

a. Create a connection object.


b. Create an adapter by passing the string query and the connection object as parameters.
c. Create a new object of dataset.
d. Call the Fill method of the adapter and pass the dataset object.

Example:
VB.NET Code:o
Dim strSQL as String
strSQL = "SELECT * from tbl"
Dim sqlCmd As New SqlCommand(strSQL, sqlConn)
Dim sda As New SqlDataAdapter(sqlCmd)
Dim ds As New DataSet
sda.Fill(ds)

c  
   


! p
pu  pp u 

 p  p
pp
p  
p p p
p  
pp
p p
p p

p  p 
p  p p
p 
p p+p#
p—p
p 
pup
p
 p 
p pp+p—p#
pp  p+p—   p

l    
     


! p
p  p p
p p 
*pp

     p
p  pp
p pp
p
pp)
p
p

ppp  p
 pp
p  
ppp
p
   p
p  p  p pp
p
pu
p
p
p

p 
    
p  p
l     
   



p  p  p3p( p pp " p p
p
 p  p p

ppp
p p
pp

.NET assemblies and resources - August 25, 2008 at 18:00 PM by Amit Satputep

c 4(%

GAC stands for global assembly cache. It is an area of memory reserved to store the assemblies
of all .NET applications that are running on a certain machine. It shares assemblies among
multiple .NET applications. The assemblies must have a strong name and must be publicly
shared to be installed in the GAC.

l  
 



p pp  p
pup  
p pp%  u
p !p  p  
p
p ppp  ppupp
  
p  p  pp 4 p
p u 
p
ppp 
pp
p
   

p
 p—pp

p
p
p ppp 
pp

pu pp
p pp
(p p p
p
p
p  p    p p 4
pp 
pp

p p
pu
p p
  pp pu p
p
p
p 
pp

p
 p  p u 
pp

pp " " p
pup
p  pupp pp
p
     

(

p p p 
p p
p  p p p p
p  p
p 
pp pu p
 p pp p
p$ p  p p p 
p
p 
pp pu p
p p

p

ppp
p p

.NET assemblies - August 25, 2008 at 18:00 PM by Amit Satpute

l( 

An Assembly is a collection, either an executable (.exe) or a dynamic link library (.dll), that
forms a logical unit of functionality and built to efficiently work together. .NET Framework can
be used to compile assemblies

Вам также может понравиться