Tuesday, February 23, 2010

Difference between Dataset and DataAdapters?

Dataset store a copy of data from the databases tables. However, Datasets cannot directly retrieve data from the Database. DataAdapters are used to link Databases with DataSet. If we see diagrammatically,

DataSet <- DataAdapter <- DataProvider <- Database

Difference between Data Set and Data Binding?

DataSet store a copy of data from the database tables.

Data Binding is binding controls to data from databases. With data binding we can bind control to a particular column in a table from the database or we can bind the whole table to the data grid. Data binding provides simple, convenient, and powerful way to create a read/write link between the controls on a form and the data in their application. Generally, Dataset don’t maintain a current record that is displayed in bound controls.

What is difference between Response.Redirect and Server.Transfer?

Response.Redirect simply sends a message down to the browser, telling it to move to another page. So, you may run code like:
Response.Redirect(“WebForm2.aspx”)
Or
Response.Redirect(http://www.google.com)
To send the user to another page.

With a call to Response.Redirect, the server basically sends an HTTP header back to the client browser with an HTTP status code stating that the object has moved along with the new location to find it.

See the snippet of an example HTTP header below when
Response.Redirect(“somewhere/newlocation.aspx”) is called.

HTTP/1.1 302 Object moved
Server: Microsoft-IIS/5.0
Location: somewhere/newlocation.aspx

This tells the browser that the requested resource (page) can be found at a new location, namely somewhere/newlocation.aspx. The browser then initials another request (assuming it supports redirects) to somewhere/newlocation.aspx loading its contents in the browser. This results in two requests by the browser.

One ramification of this is that if the initial request was a form POST, the posted from fields are not available in the second request. Likewise query string parameters are unavailable unless the page that issues the redirect explicitly tacks them on. Also, since the browser initiates the second request, it is possible to redirect to a page on an external site.

Server.Transfer is similar in that it sends the user to another page with a statement such as Server.Transfer(“WebForm2.aspx”). However, the statement has a number of distinct advantages and disadvantages.

Firstly, transferring to another page using Server.Transfer conserves server resources. Instead of telling the browser to redirect, it simply changes the “focus” on the Web server and transfers the request. This means you don’t get quite as many HTTP  requests coming through, which therefore eases the pressure on your Web server and makes your applications run faster.

Because the “transfer” process can work on only those sites running on the server, you can’t use Server.Transfer to send the user to an external site. Only Response.Redirect can do that.

Secondly, Server.Transfer maintains the original URL in the browser. This can really help streamline data entry techniques, although it may make for confusion when debugging.

That’s not all: The Server.Transfer method also has a second parameter – “preserveFrom”. If you set this to True, using a statement such as Server.Transfer(“WebForm2.aspx”, True), the existing query string and any form variables will still be available to the page you are transferring to.

Server.Transfer transfers execution from the first page to the second page on the server. As far as the browser client is concerned, it made one request and the initial page is the one responding with content (this point often confuses new ASP.NET developers as the browser still shows the URL of the initial page even though the content is generated by the second page. It all makes sense when you understand what is happening.).

The benefit of this approach is one less round trip to the server from the client browser. Also, any posted form variables and query string parameters are available to the second page as well (however these can be cleared by passing in false for the second parameter).

One thing to be aware of is that if the first page wrote something to the Response buffer and you don’t clear it, then any output from the second page will be appended to the output of the first. This is often the cause of a weird behavior where it seems that a page is returning two different pages. Also, since the transfer happens on the server, you cannot transfer a request to an external site.

ADO.NET Objects

ADO.NET includes many objects we can use to work with data.
A) The SqlConnection Object – To interact with a database, we must have a connection to it. The connection helps identify the database server, the database name, user name, password, and other parameters that are required for connecting to the data base. A connection object is used by command objects so they will know which database to execute the command on.
B) The SqlCommand Object – The process of interacting with a database means that we must specify the actions we want to occur. This is done with a command object. We use a command object to send SQL statements to the database. A command object uses a connection object to figure out which database to communicate with. We can use a command object alone, to execute a command directly, or assign a reference to a command object to an SqlDataAdapter, which holds a set of commands that work in a group of data.
C) SqlDataReader Object - Many data operations require that we only get a stream of data for reading. The data reader object allows us to obtain the results of a SELECT statement from a command object. For performance reasons, the data returned from a data reader is a fast forward – only stream of data. This means that we can only pull the data from the stream in a sequential manner. This is good for speed, but if we need to manipulate data, then a DataSet is a better object to work with.
D) The DataSet Object – DataSet objects are in – memory representations of data. They contain multiple Datatable objects, which contain columns and rows, just like normal database tables. We can even define relations between tables to create parent –child relationships. The DataSet is specifically designed to help manage data in memory and to support disconnected operations on data, when such a scenario make sense. The DataSet is an object that is used by all of the Data Providers, which is why it does not have a Data Provider specific prefix.
E) The SqlDataAdapter Object – Sometimes the data we work with is primarily read – only and you rarely need to make changes to the underlying data source. Some situations also call for caching data in memory to minimize the number of database calls for data that does not change. The data adapter makes it easy for us to accomplish these things by helping to manage data in a disconnected mode. The data adapter fills a DataSet object when reading the data and writes in a single batch when persisting changes back to the database. A data adapter contains a reference to the connection object and opens and closes the connection automatically when reading form or writing to the database. Additionally, the data adapter contains command object references for SELECT, INSERT, UPDATE, and DELETE operations on the data. We will have a data adapter defined for each table in a DataSet and it will take care of all communication with the database for us. All we need to do is tell the data adapter when to load form or write to the database.

What is Data Providers?

What is Data Providers?ADO.NET provides a relatively common way to interact with data sources, but comes in different sets of libraries are called Data Providers and are usually named for the protocol or data source type they allow we to interact with.
ADO.NET Data Providers are class libraries that allow a common way to interact with specific data sources or protocols. The library APIs have prefixes that indicate with provider they support.


Provider Name
API prefix
Data Source Description
ODBC Data Provider
Odbc
Data Sources with an ODBC interface. Normally older data bases.
OleDb Data Provider
OleDb
Data Sources that expose an OleDb interface, i.e. Access or Excel.
Oracle Data Provider
Oracle
For Oracle Databases.
SQL data Provider
Sql
For interacting with Microsoft SQL Server
Borland Data Provider
Bdp
Generic access to many databases such as Interbase, SQL Server, IBM DB2, and Oracle.

What is ADO.NET?

ADO.NET is an object – oriented set of libraries that allows us to interact with data sources. Commonly, the data source is a database, but it could also be a text file, an Excel spreadsheet, or an XML file.

With the release of the .NET Framework, Microsoft introduced a new data access model, called ADO.NET. The ActiveX Data Object acronym was no longer relevant, as ADO.NET was not ActiveX, but Microsoft kept the acronym due to the huge success of ADO. In reality, it’s an entirely new data access model written in the .NET Framework.

ADO.NET supports communication to data sources through both ODBC and OLE-DB, but it also offers another option to using database-specific data providers. These data providers offer greater performance by being able to take advantage of data – source – specific optimizations. By using custom code for the data source instead of the generic ODBC and OLE-DB code, some of the overhead is also avoided. The original release of ADO.NET included a SQL provider and an OLE-DB provider, with the ODBC and Oracle. Many vendors have also written providers for their database since. Figure shows the connection options available with ADO.NET.
                                             Application
                                                  
                                           
                                              ADO.NET

                                              OLE DB

                                              Data Store




 With ADO.NET, the days of the recordset and cursor are gone. The model is entirely new, and consists of five basic objects:
Connection – The Connection object is responsible for establishing and maintaining the connection to the data source, along with any connection – specific information.
Command – The Command object stores the query that is to be sent to the data source, and any applicable parameters.
DataReader – The DataReader object provides fast, forward – only reading capability to quickly loop through the records.
DataSet – The DataSet object, along with the child objects, is what really makes ADO.NET unique. It provides a strong mechanism for disconnected data. The DataSet never communicates with any data source and is totally unaware of the source of the data used to populate it. The best way to think of it is as an in-memory repository to store data that has been retrieved.
DataAdapter – The DataAdapter object is what bridges the gap between the DataSet and the data source. The DataAdapter is responsible for retrieving the data from the Command object and populating the DataSet with the data returned. The DataAdapter is also responsible for persisting changes to the DataSet back to the data source.

    ADO.NET made several huge leaps forward. Arguably, the greatest was the introduction of truly disconnected data access. Maintaining a connection to a database server such as MS SQL Server is an expensive operation. The server allocates resources to each connection, so it’s important to limit the number of simultaneous connections. By disconnecting form the server as soon as the data is retrieved, instead of when the code is done working with that data, that connection becomes available for another process, making the application much more scalable.

Another feature of ADO.NET that greatly improved performance was the introduction of connection pooling. Not only is maintaining a connection to the database to the database an expensive operation, but creating and destroying that connection is also very expensive. Connection pooling cuts down on this. When a connection is destroyed in code, The Framework keeps it open in a pool. When the next process comes around that needs a connection with the same credentials, it retrieves it from the pool, instead of creating a new one.
  
Several other advantages are made possible by the DataSet object. The DataSet object stores the data as XML, which makes it easy to filter and sort the data in memory. It also makes it easy to comvert the data to other formats, as well as easily persist it to another data store and restore it again.

ASP.NET vs. ASP

ASP.NET has better language support, a large set of new controls, XML – based components, and better user authentication.
ASP.NET provides increased performance by running compiled code.
ASP.NET code is not fully backward compatible with ASP.

How Does ASP.NET Work?

 •    When a browser requests an HTML file, the server returns the file
•    When a browser requests an ASP.NET file, IIS passes the request to the ASP.NET engine on the server
•    The ASP.NET engine reads the file, line by line, and executes the script in the file
•    Finally, the ASP.NET file is returned to the browser as plain HTML

Wednesday, February 17, 2010

Difference between Delete and Truncate?

•    Delete table is a logged operation, so the deleting of each row gets logged in the transaction log, which make it slow.
•    Truncate table also deletes all the rows in a table, but it won’t log the deletion of each row, instead it logs the de-allocation of the data pages of the table, which makes it faster. Of course, truncate table cannot be rolled back.
•    Truncate table is functionally identical to delete statement with no “where clause”. Truncate table is faster and uses fewer system and transaction log resources than delete.
•    We cannot use truncate tale on table referenced by a foreign key constraints, instead, use delete statement without a where clause. Because truncate table is not logged, it cannot active a trigger.
•    Truncate table nay not be used in tables participating in an indexed view.
•    Truncate is a DDL command and cannot be rolled back. All of the memory space is released back to the server.
•    Delete is a DML command and can be rolled back.

What does AutoPostBack do?

As the name implies, it automatically posts the page back to the server when the value of the control changes.

Difference between GridView and ListView?

The GridView control is used to display the values of a data source in a table. Each column represents a field, while each row represents a record. The GridView control supports the following features:
•    Binding to data source controls, such as SqlDataSource.
•    Built-in sort capabilities.
•    Built-in update and delete capabilities.
•    Built-in paging capabilities.
•    Built-in row selection capabilities.
•    Programmatic access to the GridView object model to dynamically set properties, handle events, and so on.
•    Multiple key fields.
•    Multiple data fields for the hyperlink columns.
•    Customizable appearance through themes and styles.
•    To learn about the other data-bound controls that are available in ASP.NET, see ASP.NET Data-Bound Web Server Controls Overview.

The ListView control is used to display the values from a data source. It resembles the GridView control, except that it displays data by using user-defined templates instead of row fields. Creating your own templates gives you more flexibility in controlling how the data is displayed.
The ListView control supports the following features:
•    Support for binding to data source controls such as SqlDataSource, LinqDataSource, and ObjectDataSource.
•    Customizable appearance through user-defined templates and styles.
•    Built-in sorting capabilities.
•    Built-in update and delete capabilities.
•    Built-in insert capabilities.
•    Support for paging capabilities by using a DataPager control.
•    Built-in item selection capabilities.
•    Programmatic access to the ListView object model to dynamically set properties, handle events, and so on.
•    Multiple key fields.

Difference between GridView and FormView?

GridView is intended to primarily to display/update multiple records. It's considered a replacement for the DataGrid control from .NET 1.1.
Formview is intended for insert/update/view of a single record.

Difference between GridView and DetailsView?

GridView is intended to primarily to display/update multiple records. It's considered a replacement for the DataGrid control from .NET 1.1.
DetailsView is intended for the displaying of a single record with optional support for paging and navigation.

Tuesday, February 16, 2010

What is Data Binding?

Data binding is one of those terms that states exactly what it is. It is a process of binding data to an ASP.NET 3.5 control. The data source that makes the most sense to bind is the data from a table in a database, but any kind of data can be bound using data binding. For example, we can bind values from items in an array or from a simple variable. Likewise, we can usefully bind data from a relational database or a single table.

On the ASP.NET side of the equation, the binding tag is simplicity itself. The tag is assigned to a control property. It has the following format:
<%# dataSource %>

The data source can be as simple as a function called in the C# portion of the application, or it may use a special ASP.NET function. For example:
<%# DataBinder.Eval(Container.DataItem, “FieldName”) %>

It is part of a larger data access application that uses a set of data binding tags employed with a Repeater control and multiple fields. If we prefer, we can use the shorter version that does not show the fuller object path:
<%# Eval(“FieldName”) %>

What is ListView?

ListView control offers a good deal of flexibility in styling a page. Using ListView, we get a lot more control over how our output looks. In effect, it is a styling control of sorts because we can use the full range of CSS that is now available in Visual Studio 2008.

To effectively use the ListView, we need to include a <LayoutTemplate> tag, and within the tag’s container, we add a PlaceHolder control with the ID named itemContainer:

<LayoutTemplate>
   <some style>
        <asp:PlaceHolder ID=”itemContainer” runat=”server”/>
</some style>
</LayoutTemplate>

All of the displayed data are styled by the style added in the <LayoutTemplate> and then placed in the PlaceHolder control.

Individual styling done in the <ItemTemplate> overrides the style from the <LayoutTemplate>, but with good planning and the full control that the ListView provides, the difference need not be at odds. In fact, the idea of the ListView is to give the designer both the flexibility and general layout features needed in design.

The sample application users one CSS style within the layout (generating a yellow background) and another CSS style for the names to be listed. The e-mail addresses that accompany the names use the default style, but are still cast on a yellow background.

What is DataList?

The DataList control is a lot like the Repeater control insofar as binding data in concerned. However, using a DataList control is when we need a single-column list. For Example, suppose we’re setting up a networking party with donors to a political campaign. Each donor will wear a nametag with his or her e-mail address so that the participants can easily exchange e-mail contact. The format for each nametag should look like the following:
   Donor’s Name: Mary Smith
   Email: ms@msmith.com
Now everyone can see that the other people are fellow donors and can see their e-mail address for future contact.

We will find using the DataList control very simple compared with the Repeater in conjunction with HTML tables. Because we only have a single column, all of our formatting can be done without worry about multiple columns or any table tags. For example, we can format the text within <ItemTemplate> container pretty much as we would HTML:

<ItemTemplate>
<strong>Field Description:</strong>
<%# Eval(“FieldName”) %>
</ItemTemplate>
Stacked up in a single column, each record needs to be separated. Using the <SeparatorTemplate>, we can make sure that the viewer can tell where one record begins and the previous one ends. Depending on what we’re doing with our data, our separator can just add vertical space or provide instructions.

What is Repeater?

The Repeater web control is another one of those self-describing objects. Used with data binding, The Repeater acts like a loop repeating statements. However, instead of repeating statements, it repeats a table – making routine so that as long as data are available, it repeats table rows. The table rows on the screen represent the table rows (records) in a table database.

The SqlDataReader is the data source for the binding operation from the data in the database table.

Monday, February 15, 2010

How to connect with database, execute command and read data in ADO.NET?

Basically we need three Classes in ADO.NET; these are SqlConnection, SqlCommand, SqlDataReader.
Following are the parameter which is needed for SQLConnection
1)    Server name (for example xyz.com)
2)    User ID (the username for the database)
3)    Password (the password for the database)
4)    Name of database (only the database name – not a table name)
Example: -
private SqlConnection hookup;
------------
hookUp = new SqlConnection(“Server=xyz.com;uid=uname;pwd=pass;database=databaseName”);

SqlCommand: The Command to Query
The SqlCommand is a class to gather up our SQL commands and send them to the server via the connection we have established using SqlConnection. The general format is

SqlCommand(“SQL query”, myConnection)

SqlDataReader: Shows What You Found
This is a command which read the results of a table query and return the database contents in such a way that they can be passed to variables and sent to ASP.NET web controls. The SqlDataReader instance uses the SqlCommand instance to launch the reader that returns array elements of the query data from the table. The element values can then be passed to variables and on to web controls or we can pass the element values directly to the controls. It has the following format:

private SqlDataReader reader;
---
reader = sqlCmd.ExecuteReader();
while (reader.Read())
{
var1 = Convert.ToString(reader[“Field1”]);
var2 = Convert.ToString(reader[“Field2”]);
WebControl.Text += var1 + var2 + “<br/>”;
}
Reader.Close();

What is difference between authentication and authorization?

  • Authentication is the mechanism whereby systems may securely identify their users. Authentication systems depend on some unique bit of information known only to the individual being authenticated and the authentication systems. Authorization is the mechanism by which a system determines what level of access a particular authenticated user should have to secured resources controlled by the system.
  • When a user logs on to an application/system, the user is first Authenticated, and then Authorized.

What is authorization?

Authorization determines whether an identity should be granted access to a specific resources. In ASP.NET, there are two ways to authorize access to given resources:
1)    File authorization – File authorization is performed by the FileAuthorizationModule. It checks the access control list (ACL) of the .aspx  or .asmx handler file to determine whether a user should have access to the file. ADL permission are verified for the user’s windows identity (if windows authentication is enables) or for windows identity of the ASP.NET process.
2)    URL authentication – URL authentication is performed by the UrlAuthorizationModule,  which maps users and roles to URLs in ASP.NET applications. This modules can be used to selectively allow or deny access to arbitrary parts of an application (typically directories) for specific users or roles.
Using URL Authorization: -
With URL authorization, we explicitly allow or deny access to a particular directory by user name or role. To do so, we create an authorization section in the configuration file for that directory. To enable URL authorization, we specify a list of users or roles in the allow or deny elements of the authorization section of a configuration file. The permission established for a directory also apply to its subdirectories, unless configuration files in a subdirectory override them.

The following shows the syntax for the authorization section: -
<authorization>
    <[allow | deny] users roles verbs/>
</authorization>

The allow or deny element is required. We must specify either users or the roles attribute. Both can be included, but both are not required. The verbs attribute is optional.

The allow or deny elements grant and revoke access, respectively. Each element supports the attributes shown the below:
Users: - Identifies the targeted identities (user accounts) for this element. Anonymous users are identified using a question mark (?). We can specify all authenticated user using as asterisk (*)
Roles: - Identifies a role ( a RolePrincipal object) for the current request that is allowed or denied access to the resources.
Verbs: - Defines the HTTP verbs to which the action applies, such as GET, HEAD, and POST. The default is “*”, which specifies all varbs.

The following example grants to the Kim identity and members of the Admins role, and denies access to the John identity (unless the John identity is included in the Admins role) and to all anonymous users:
<authorization>
<allow users=”Kim”/>
<allow roles=”Admins”/>
<deny users=”John”/>
<deny users=”?”/>
</authorization>
The following authorization section shows how to allow access to the Johan identity and deny access to all other users:
<authorization>
<allow users=”John”/>
<deny users=”*”/>
</authorization>
We can specify multiple entities for both the users and roles attributes by using a comma – separated list, as shown in the following example: -
<allow users=”John, Kim, contoso\Jane”/>
Note that if you specify a domain account name, the name must include both the domain and user name (contoso\Jane).

The following example allows all users to perform an HTTP GET for a resource, but allows only the Kim identity to perform a POST operation:
<authorization>
<allow verbs=”GET” users=”*”/>
<allow verbs=”POST” users=”Kim”/>
<deny vervs=”POST” users=”*”/>
</authorization>

Rules are applied as follows: -
•    Rules contained in application – level configuration files take precedence over inherited rules. The system determines which rule takes precedence by constructing a merged list of all rules for a URL, with the most recent rules (those nearest in the hierarchy) at the head of the list.

•    Given a set of merged rules for an application, ASP.NET starts at the head of the list and checks rules until the first match is found. The default configuration for ASP.NET contains an <allow users=”*”> elements, which authorizes all users. (By default, this rule is applied last). If no other authorization rules match, the requested is allowed. If a match is found and the match is a deny element, the request is returned with the 401 HTTP status code. If an allow element matches, the module allows the request to be processed further.

What is difference between form authentication and window authentication?

Following are difference between windows authentication and form authentication:-
1)    Widows authentication uses windows accounts whereas forms authentication maintains its own user lists.
2)    Windows authentication best suited for the application which is meant for corporate users whereas form authentication is preferable for the applications which have diversified users from several places.
3)    User lists for windows authentication are found in <authorization> element whereas in case of form authentication, lists are there in <credential> element of web.config file.

How many types of authentication do you know?

The ASP.NET Framework supports three types of authentication: -
  • Window authentication
  • .NET passport authentication
  • Forms authentication
Note: - A particular application can have only one type of authentication enabled. We can’t, for example, enable both window and forms authentication at the same time.
  •     Window authentication: - It is enabled by default. When Window authentication is enabled, users are identified by their Microsoft Windows account names. Roles correspond to Microsoft Windows groups.

Windows authentication delegates the responsibility of identifying users to IIS. IIS can be configured to use Basic, Integrated Windows or Digest authentication.

 There are four types of window authentication methods:-
1)    Anonymous Authentication – IIS allows any user.
2)    Basic Authentication – A windows username and password has to be sent across the network (in plain text format, hence not very secure).
3)    Digest Authentication – Same as Basic Authentication, but the credentials are encrypted. Works on IE5 or above.
4)    Integrated Windows Authentication – Relies on Kerberos technology, with strong credential encryption.


  •   .NET Passport authentication: - It is the same type of authentication used to Microsoft websites such as MSN and Hotmail. If we want to enable users to log in to our application by using their existing Hotmail usernames and passwords, then we can enable .NET passport authentication.
There are two types of .NET passport authentication:-
1)    FileAuthentication – this depends on the NTFS systems for granting permission.
2)    UrlAuthentication – Authorization rules may be explicitly specified in web.config for different web URLs.

    Note: - We must download and install the Microsoft .NET passport SDK, register with Microsoft, and pay Microsoft a fee before we can use .NET passport authentication.
    •    Form authentication: - When forms authentication is enabled, user are typically identified by a cookie. When a user is authenticated, an encrypted cookie is added to the user’s browser. As the user moves from pages to pate, the user is identified by the cookie.

    When Forms authentication is enabled, users and role information is stored in a custom data store.  We can store user information anywhere then we want. For example, we can store usernames and passwords in a database, an XML file, or even a plain text file.

    In ASP.NET1.x, after enabling Forms authentication, we had to write all the code for storing and retrieving user information. When building an ASP.NET 3.5 application, on the other hand, we can let ASP.NET Membership do all this work for us. ASP.NET Membership can handle all the details of storing and retrieving user and role information.

    We can enable a particular type of authentication for an application in an application’s root web configuration file.

      What is authentication?

      Authentication refers to the process of identifying user who they are. It is the process of obtaining identification credential such as name and password form a user and validating those credentials against some authority. If the credentials are valid, the entity that submitted the credentials is considered an authenticated identity. Once an identity has been authenticated, the authorization process determines whether that identity has access to a given resource.

      What is a MapPath?

      When we are working on a remote server, we may not know the exact path. Using the MapPath method, we can map a specified virtual path to a physical path. If we do not know the exact path, simply we can enter the name of the text file we wish to create, and it is created in our root directory with the ASPX and CS file of our web site. The format is

      using (StreamWriter swInstance = new StreamWriter MapPath(“shri.txt”))
      {
      ……

      }

      File and Directory related class, method and operation.

      1) StreamWriter class under System.IO namespace
      Example: - using(StreamWriter swInstance = new StreamWriter(“FileName.txt”))
      {… ..}
      2) StreamWriter.Write() method
      3) StreamWriter.WriteLine() method
      4) File.CreateText() operation
      5) File.AppendText() operation
      6) StreamReader class
      Example: - using(StreamReader readMe = new StreamReader(“FileName.txt”))
      {… ..}
      7) StreamReader.ReadLine() mehod: - This is the key method to read the contents of a text file. Text is treated as chunks of data demarcated by line breaks. More specifically, the line breaks are either a carriage return (“\r”) or line feed (“\n”), or a combination of carriage return and by a line feed (“\r\n”).
      8) DirectoryInfo class: - using DirectoryInfo class, we can create, move, and display directories in addition to viewing files. For the purpose of reading text files, all we need to do is to find the directory with our files. There are two method under DirectoryInfo class first is DirectoryInfo.FetDirectories() and second is DirectoryInfo.GetFiles().
      • Locating and Displaying Directories: - In using the DirectoryInfo class, an instance is created using a starting point in the directory structure. For example, the following shows the format for the root C: directory:
      DirectoryInfo dir = new DirectoryInfo(@”C:\\”);

      To view the directories at the C: root, you can iterate through the DirectoryInfo instance to pull out the full set of directories using the following format:

      Foreach(DirectoryInfo dirInfoInstance in dirInfo.GetDirectories()) … .

      • Locating and Displaying Files: - If we use files for storing different kinds of data, sometimes we might forget the location of the file or its name. Using the DirectoryInfo.GetFiles() method, we can retrieve the filenames in a given directory. The FileInfo class is similar to the DirectoryInfo class, except it is used with files rather than directories. However, we can work with both to locate a file within a directory. When iterating through a DirectoryInfo object, instead of using a DirectoryInfo instance to locate a specific directory, you use a FileInfo object as the element to retrieve the files in the directory. The format
      Foreach(FileInfo fileInfo in directoryInfoInstance.GetFiles())
      Finds the files in the specified instance of the DirectoryInfo method GetFiles().


      When we enter data into a text file using the WriteLine() method, it automatically enters a line break, so when you use the ReadLine(), it knows what text is considered to be a separate line. Text entered in other ways marks the end of the line with either of the other two acceptable markers that ReadLine() can find.

      Thursday, February 11, 2010

      How many types of login control do you know?

      List of Login controls: -
      •     Login
      •     LoginView
      •     PasswordRecovery
      •     LoginStatus
      •     LoginName
      •     CreateUserWizard
      •     ChangePassword

      Explain about Membership Security

      For storing security, ASP.NET 3.5 provides a system for storing username and encrypted passwords in a special database. We can set this security in different ways using Visual Studio 2008. Many of the most important elements are set up automatically, including with the default name as ASPNETDB.MDF.
      The password is stored in a database, ASPNETDB.MDF, in a table named aspnet_Users

      Examples: -


      --more code
      <system.web>
      <authentication mode="Forms" />
      <authorization>
      <deny users="?"/>
      </authorization>
      --more code


      <!-- Web.config for Registration -->
      <configuration>
      <system.web>
      <authorization>
      <allow users="*"/>
      </authorization>
      </system.web>
      </configuration>

      Friday, February 5, 2010

      How to do Forms Authentication Configuration?

      The first step in protecting our site is to develop a web.config file that has both an authentication and an authorization filter. If we use Forms authentication, all users are sent to a login page in their first visit. Once they have been authenticated, they can return to the site without having to go through a login process.

      With Forms authentication, no matter what page the user requests, he is automatically sent to a login page with the default name login.aspx. Once he fills out the login information, he is allowed to view the page requested initially. The following web.config file shows the required tags:
      <configuration>
      <system.web>
      <authentication mode ="Forms" />
      <authorization>
      <deny users="?" />
      </authorization>
      </system.web>
      </configuration>
      As noted, the authentication mode set to Forms automatically directs the browser to open a file named login.aspx, but if we want to change that to a specific file with a name we prefer, we can specify which one we want by using the tags:
      <authentication mode="Forms">
      <forms loginUrl="mySpecialFile.aspx" />
      </authentication>
      Most importantly, the site uses the FormsAuthentication class from System.Web.Security namespace. One method is
      FormsAuthentication.RedirectFromLoginPage()
      Which takes the original requested URL and sends the requested page if the login is successful. It uses the following format:
      FormsAuthentication.RedirectFromLoginPage(string, Boolean);
      The important feature of this method is that ASP.NET automatically adds the return URL when the browser is redirected to the login page. The string parameter is a username and the Boolean is whether or not the login will store a persistent cookie. The false Boolean indicates that it will not store a cookie.
      This whole state is set up when the web.config file indicates that anonymous users will not be permitted and the authentication mode is set to Forms.
       Example: -
      Login.aspx
      <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Login.aspx.cs" Inherits="Login" %>

      <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

      <html xmlns="http://www.w3.org/1999/xhtml">
      <head runat="server">
      <style type="text/css">
      body
      {
          font-family:Verdana;
          font-size:11pt;
          color:Navy;
      }
      h1
      {
          font-size:18pt;
          font-weight:bold;
         
      }
      </style>
          <title>Login</title>
      </head>
      <body>
          <form id="form1" runat="server">
          <div>
          <h1>Login Page</h1>
          <asp:TextBox ID="uname" runat="server">Name</asp:TextBox><p></p>
          <asp:TextBox ID="pw" runat="server" TextMode="Password">&nbsp;Password</asp:TextBox><p>
          </p>
          <asp:Button ID="Button1" runat="server" Text="Login" OnClick="DoLogin" /><p></p>
          <asp:Label ID="BadLog" runat="server" ForeColor="#FF3300"></asp:Label>
         
          </div>
          </form>
      </body>
      </html>

      Login.aspx.cs
      using System;
      using System.Collections;
      using System.Configuration;
      using System.Data;
      using System.Linq;
      using System.Web;
      using System.Web.Security;
      using System.Web.UI;
      using System.Web.UI.HtmlControls;
      using System.Web.UI.WebControls;
      using System.Web.UI.WebControls.WebParts;
      using System.Xml.Linq;

      public partial class Login : System.Web.UI.Page
      {
          protected void Page_Load(object sender, EventArgs e)
          {

          }
          protected void DoLogin(object sender, EventArgs e)
          {
              if (uname.Text == "kishore" && pw.Text == "shri81")
              {
                  FormsAuthentication.RedirectFromLoginPage(uname.Text, false);
              }
              BadLog.Text = "Check your username and password. Not logged in.";

          }
      }

      What is web.config file?

      It is an XML file with the .config extension. As we have been developing ASP.NET applications, one of the files automatically generated is a little web.config file with information about the web site’s environment.  It contains all kinds of information related to web site. For example, that our by which version of .NET our application has been developed. However, the most basic web.config file is one that comes up in an error message that reads as follows:
      <!-- Web.config Configuration File -->
      <configuration>
      <system.web>
      <customErrors mode="Off"/>
      </system.web>
      </configuration>
      We can use multiple web.config files. When we want users to have access to some files and not others, one way to control access is to use multiple web.config files. A web.config file in the root directory affects all of the files, but if we place a different web.config file in subdirectory, it will override the root web.config file.
      For example, suppose we have the following directory structure:
      Root (web.config)
          ASPNET
              Display
              Dreamer
              MapFile
              Special
                  Lists(web.config)
      All of the files and folders in the root directory are subject to the directives in the root web.config tile. However, in the Special directory is another web.config file that is open to all users:
      <configuration>
      <system.web>
      <authorization>
      <allow users="*" />
      </authorization>
      </system.web>
      </configuration>
      The <allow> node indicates which users have access, and the asterisk (*) is an “all” wildcard symbol.

      What is and AsyncPostBackTrigger object?

      If we call any events based on controls outside of the UpdatePanel, the whole page is reloaded unless we take certain steps to prevent that from happening.
      Why place controls outside of the UpdatePanel container if they are to be used for working with events inside the UpdatePanel container. We may be working with an existing site that originally did not have Ajax functionality. Instead of moving the different controls inside the UpdatePanel container, we just want their events to have an effect on the UpdatePanel controls.
      Fortunately, the solution for using Ajax with control events outside the UpdatePanel container is relatively simple. We can use the <Triggers> tag and the AsyncPostBackTrigger object to listen to the events of controls of the UpdatePanel container. The following shows the relevant code structure:
      <Triggers>
      <asp:AsyncPostBackTrigger ControlID="ControlName"
      EventName="EventName" />
      </Triggers>
      By default, the trigger container goes inside the UpdatePanel container but outside of the <ContentTemplate> container.
      In this context the EventName refers to the name of the event launched by the control, and not to the target function in the C# code. For example, a Button control may have a “Click” event, so the assignment
      EventName="Click"
      Would mean that from inside the UpdatePanel container, the control outside the container is set up as a non - Ajax control. Then within UpdatePanel container, the triggers just listen for the appropriate event from the named control; only the updated material, and not the whole page, is updated.

      Please explain about Ajax Timer Control.

      Timer Control is one that calls a C# function in timed intervals. This is a perfect application for bringing in information based on a timer but not reloading the entire page.
      Timer Properties: - Not only is the Ajax Timer control useful, but it also is easy to use. With only four properties, ID, Enabled, EnableViewState, and Interval, we can set it up very quickly. For most application the only property that really needs setting is the Interval. The Interval value is set in microseconds. So, for example, if we want a 22 – second interval, we would set the value to 22000.
      The control has several different events as well, but for most uses, all we need is the OnTick event. The OnTick event calls a C# event handler (method) at the assigned Interval. By placing the Timer inside UpdatePanel container, by default it is the Ajax event handler for the UpdatePanel.

      What is AJAX?

      AJAX is a relatively new Internet technology that grew out of combining JavaScript and XML. The term itself is an acronym for “Asynchronous JavaScript and XML.” The key feature of Ajax can be seen when the client requests new information. Instead of sending a whole new page, Ajax sends only the required new information. That means all of the buttons, text, graphics, and other objects that may be on a page do not have to be shipped over the Internet and reloaded into our browser.
      ASP.NET 3.5 AJAX is easy to use and efficient. Using Visual Studio 2008, we can create an Ajax web site using only two Ajax controls. The main Ajax control is what is called the UpdatePanel, where all of the elements in our Ajax application can be placed. The other control is the ScriptManager. The ScriptManager control is required to access the Ajax Library and partial page rendering without post – back.

      Wednesday, February 3, 2010

      What are difference between Repeater, DataList and GridView?

      Please find below chart for difference between Repeater, DataList and GridViewr: -
      Feature                        Repeater    DataList    GridView
      Table layout                 No              No            Yes
      Flow layout                  Yes             Yes           No
      Column layout              No              Yes           No
      Style properties            No              Yes           Yes
      Templates                    Yes             Yes           Columns/optional
      Select/ Edit/Delete        No              Yes           Yes
      Sort                             No               No            Yes
      Paging                          No               No           Yes

      Difference between DataGrid and GridView?

       GridView Control has replaced the ASP.NET 1.1 DataGrid Control.

      The GridView and the DataGrid controls have a different foundation. To enable easy migration from existing pages, the GridView preserves the DataGrid object model as much as possible. However, we shouldn’t expect 100 percent compatibility between DataGrid-based code and new GridView-based code.

      Another key difference between the DataGrid and GridView controls lies in the adaptive user interface.  Unlike the version 1.x DataGrid, the GridView can render on mobile devices, too. In other words, to build reports on mobile devices, we can use the same grid control we would use for desktop pages. The DataGrid version 2.0 can also render adaptively, but its UI capabilities are not quite as rich as those of the GridView.

      In ASP.NET 2.0, the DataGrid control has been enhanced to support common control feature such as themes and personalization. In addition, the new DataGrid control can be populated by a data source control. Remember, though, that a DataGrid can only bind to a data source object for the purpose of reading data. To actually modify the underlying data source, some user-defined code is still required. In contrast, the GridView control takes advantage of the capabilities of the underlying data source and automatically deletes or updates records. Note that the GridView control also supports the classic binding mechanism based on the DataSource property and the DataBind method.

      How many Data Display controls do you know?

      Followings are Data Display Controls: -
      GridView
      DataList
      DetailsView
      FormView
      ListView
      Repeater

      What is base class of page in ASP.NET?

      Single – File Pages: - In a single file page, the markup, server – side elements, and event-handling code are all in a single .aspx file. The base class of single – file page is Page class which is under System.Web.UI namespace.
      Code – Behind Pages: - In the code – behind model, the page’s markup and server-side elements, including control declarations, are in an .aspx file, while our page code is in a separate code file. The code file contains a partial class – that is, a class declaration with the keyword partial indicating that it contains only some of the total code that makes up the full class for the page. In the partial class, we add the code that our application requires for the page. This typically consists of event handlers, but can include any methods or properties that we need. The code – behind file contains a partial class that inherits from a base page class. The base page class can be the Page class, or it can be another class that derives for Page.

      How many securities related frameworks available in ASP.NET?

      The ASP.NET Framework includes four frameworks related to security:
      • ASP.NET Authentication: - Enables us to identify users.
      • ASP.NET Authorization: - Enables us to authorize users to request particular resources.
      • ASP.NET Membership: - Enables us to represent users and modify their properties.
      • Role Manager: - Enables us to represent user roles and modify their properties.

      Tuesday, February 2, 2010

      What is difference between master page and web user control?

      Master Page: - A master page enables us to share the same content among multiple content pages in a website. We can use master page to create a common page layout. For example if we want all the pages in our web site to share a three – column layout, we can create the layout once in a Master Page and apply the layout to multiple content pages.

      We can also use Master Page to display common content in multiple pages. For example, if we want to display a standard header and footer in each page in our website, then we can create the standard header and footer in a Master Page.

      If we need to add a new page to our website that looks just like the other pages in our website, then we simply need to apply the same Master Page to the new content page. If we decide to completely modify the design of our website, we do not to change every content page. We can modify just a single Master Page to dramatically change the appearance if all the pages in our application.

      <%@ Master Language="C#" AutoEventWireup="true" CodeFile="MultipleContent.master.cs" Inherits="MultipleContent" %>

      <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

      <html xmlns="http://www.w3.org/1999/xhtml">
      <head runat="server">
          <title>Multiple Content Master Page</title>
          <asp:ContentPlaceHolder id="head" runat="server">
          </asp:ContentPlaceHolder>
      </head>
      <body>
          <form id="form1" runat="server">
          <div>
          <img src="apress.jpg" alt="aprees" /><br />
              <asp:ContentPlaceHolder id="MainContent" runat="server">
             
              </asp:ContentPlaceHolder>
              <i>
              <b>OTHER LINKS</b>
              <br />
              <asp:ContentPlaceHolder ID="OtherLinksContent" runat="server">
              </asp:ContentPlaceHolder>
              This is a simple footer.
              </i>
          </div>
          </form>
      </body>
      </html>
      There are two special things about the master page. First the file contains < %@ Master %> directive instead of the normal <%@ Page %> directive. Second the Master Page includes ContentPlaceHolder controls.

      When the master page is merged with a particular content page, the content from the content page appears in the areas marked by ContentPlaceHolder controls. We can add as many ContentPlaceHolders to Master Page as we need.

      Note: - 1) There are some things that we can’t do with master page that we can do in a content page. For example, we can’t cache a master page with the OutputCache directive. We also can’t apply a theme to a Master page.
          2) The Master Page uses cascading style sheets to create the page layout. We could strive to avoid using HTML tables for layout. HTML tables should be used only to display tabular information.
      3) The content page does not contain any of the standard opening and closing XHTML tags. All these tags are contained in the Master Page. All the contents contained in the content page must be added with content controls.
      4) We must palace all the content contained in a content page within the Content Controls. If we attempt to palace any content outside these controls, you get an exception.
      5) The content control includes a ContentPlaceHolderID property. This property points to the ID of a ContentPlaceHolder control contained in the Master Page.
      6) Within a Content control we can place anything that we could normally add to an ASP.NET page, including XHTML tags and ASP.NET controls.
      <%@ Page Language="C#" MasterPageFile="~/MultipleContent.master" AutoEventWireup="true" CodeFile="MultipleContentPage.aspx.cs" Inherits="MultipleContentPage" Title="Content Page" %>
      <asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
      This is the generic content for this page. Here you might provide some site
      specific text......
      </asp:Content>

      <asp:Content ID="Content2" ContentPlaceHolderID="OtherLinksContent" runat="server">
      Here's a <a href="http://www.prosetch.com">link</a><br />
      </asp:Content>

      The master page is associated with the content page through the MasterPageFile attribute included in the <%@ Page %> directive. This attribute contains the virtual path to a Master Page.

      When building a large website, we might need to create multiple levels of Master Pages. For example, we might want to create a single site - wide Master Page that applies to all the content pages in your website. In addition, we might need to create multiple section – wide master page that apply to only the pages containded in a particular section.We can nest master page as many levels as we need.

      Web User Control: - A Web User Control enables us to build a new control from existing controls. By taking advantage of User controls, we can easily extends the ASP.NET Framwork with our own custom controls.

      Imaging, for example, that we need to display the same address form in multiple pages in a web application. The address form consists of several TextBox and validation controls for entering address information. If we want to avoid declaring all the TextBox and Validation control in multipls pages, we can wrap these controls inside a Web User Control.

      Anytime we discover that we need to display the same user interface elements in multiple pages, we could consider wrapping the elements inside a User Controls, we make our website easier to maintain and extend.

      Note: - 1) User controls are closely related to ASP.NET pages. Both the UserControl class and the page class derive from TemplateControl class. Because they derive from the same base class, they share many of the same methods, properties, and events.
            2) The important difference between an ASP.NET page and User control is that User Control is something that we can declare in an ASP.NET page. When we build a User Control, we are building a custom control.

      <%@ Control Language="C#" AutoEventWireup="true" CodeFile="LinkMenu.ascx.cs" Inherits="LinkMenu" %>

      <div>
          Products:<br />
          <asp:HyperLink ID="lnkBooks" runat="server"
              NavigateUrl="MenuHost.aspx?product=Book">Books</asp:HyperLink>
          <br />
          <asp:HyperLink ID="lnkToys" runat="server"
              NavigateUrl="MenuHost.aspx?product=Toys">Toys</asp:HyperLink>
          <br />
          <asp:HyperLink ID="lnkSports" runat="server"
              NavigateUrl="MenuHost.aspx?product=Sports">Sports</asp:HyperLink>
          <br />
          <asp:HyperLink ID="lnkFurniture" runat="server"
              NavigateUrl="MenuHost.aspx?product=Furniture">Furniture</asp:HyperLink>
      </div>

      Web User Controls file ends with .ascx extention. We can’t request this file directly form a web browser.
      <%@ Page Language="C#" AutoEventWireup="true" CodeFile="MenuHost.aspx.cs" Inherits="MenuHost" %>
      <%@ Register TagPrefix="apress" TagName="LinkMenu" Src="~/LinkMenu.ascx" %>

      <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

      <html xmlns="http://www.w3.org/1999/xhtml">
      <head runat="server">
          <title>Menu Host</title>
      </head>
      <body>
          <form id="form1" runat="server">
          <div>
         
              <table>
                  <tr>
                      <td>
                          <apress:LinkMenu ID="Menu1" runat="server" /></td>
                      <td>
                          <asp:Label ID="lblSelection" runat="server"></asp:Label></td>
                     
                  </tr>
              </table>
         
          </div>
          </form>
      </body>
      </html>

      The page in which we are using Web User Controls includes a <%@ Register %> directive that contains the following three attributes:
      1)    TagPrefix – Indicates the namespace that we want to associate with the User control for the current page. We can use any string that we want.
      2)    TagName – Indicates the name that we want to associate with the User Control for the current page. We can use any string that we want.
      3)    Src – Indicates the virtual pathe to the User control (the path to the .ascx file).
      Note: - Any properties that we add to a User control appears in both intellisense and the Property window.

      Monday, February 1, 2010

      How to make View State secure?

      In order to make the view state more secure, the ASP.NET @Page directive supports an attribute called EnableViewStateMac whose only purpose is detecting any possible attempt at corrupting original data.

      Drawback of View State.

      The _VIEWSTATE hidden form field can become very large. Stuffing too much data into View State can slow down the rendering of a page because the contents of the hidden field must be pushed back and forth between the web server and web browser.

      Because the view state is packed with the page, it inevitably adds a few extra kilobytes of data to the payload. A complex, real – world page – especially one that does not optimize and restrict the use of the view state – can easily find 10KB of extra stuff packed in the HTML code sent to the browser.

      Since it is passed as plain text to the client. Anybody can tamper this value, because of this you shouldn’t store any important data in the view state.

      Advantage of View State.

      View state does not require any server state resources and is simple to implement.

      Since the View State is encoded, protected, and validated, it does provide more security features than other hidden fields.

      Format of View State stored states data?

      States are saved in a Base64 encoded string only, but not encrypted.
      Note: - Please do not store sensitive data in the View State (Like credit card numbers, passwords, connection strings, etc).

      Where state of View State will store?

      View State stores the state of controls in HTML hidden fields on Client.

      What is View State?

      The HTTP protocol is a stateless protocol. Each time we request a web page from a website, we are a completely a new person.

      The ASP.NET Framework, however, manages to transcend this limitation of the HTTP protocol ASP.NET Framework uses a trick called View State. For example, if we assign a value to Label control’s Text property, the Label control retains this value across multiple page requests.

      <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTIxMDI3MzgyODNkZJzgJL2eDEmaIufBUIMhS/GE1lZs" />

      This hidden form field contains the value of the Label control’s Text property (and the values of any other control properties that are stored in View State). When the page is posted back to the server, the ASP.NET Framework rips apart this string and re-create the values of all the properties stored in View State. In this way, the ASP.NET Framework preserves the state of control properties across postbacks to the web server.

      By default, View State in enabled for every control in the ASP.NET Framework. If you change the background color of a Calendar control, the new background color is remembered across postbacks. The values of these properties are automatically stored in View State.