I am Raghuveer

In my opinion programming means thinking, and it is fun. My vision is to teach programming in more understandable manner to the students from rural background. I support programming for everyone

Installing nginx with passenger and RVM

In this post I am going to tell you how to install the nginx server with passenger to host rails applications.

Following are my configurations:
OS: Ubuntu 11.10
Ruby: 1.8.7
I am using RVM
Don't install nginx with sudo apt-get install nginx command, I face lot of problems with it..
First install Ruby 1.8.7 with RVM
Next install passenger which ever version you want, I prefer latest.
gem install passenger
The above command will install passenger for your system, now we can install either apache2 or nginx as HTTP servers. I am installing nginx here.
After installing passenger you need to run the following command
rvmsudo passenger-install-nginx-module
This is important step while installing, 
Don't run above command with sudo or without rvmsudo it won't work as expected.
The script will ask you if you want a default installation or a custom/advanced on.
I just did the default (option 1).
The script downloads and compiles nginx. It will ask you where you want it installed. I suggest /usr/local/nginx.
Don't just say /usr/local as that will create conf, html and logs directory right in /usr/local. You really want these in a nginx specific directory.
All being well the compilation and installation will go smoothly and your fresh installation of nginx will be modified for use with passenger.
If I remember the installation correctly it actually fires up nginx and leaves it running.
Check that with 'ps ax | grep nginx'
Go to your browser. 'http://localhost' should give a 'welcome to nginx' page. Look in /usr/local/nginx/logs/ for logging output.
ConfigurationI set up a symlink in /usr/local/sbin to the nginx binary so that it can be found in my regular PATH
sudo ln -s /usr/local/nginx/sbin/nginx /usr/local/sbin/nginx
You start nginx with 'sudo nginx' and shut it down with 'sudo killall nginx'. It needs to be run via sudo.
Configuring nginx is done in /usr/local/nginx/conf/nginx.conf and if you are used to Apache config files this will be a breath of fresh air. The main changes I made from the default was to set myself as the 'user' and set the worker_processes to 2. To set up a Rails application simply add a server block like this:
server {
listen 80;
server_name myapp.rvg.com;
root /Users/rvg/projects/test/public;
passenger_enabled on;
rails_env development;
}
Be sure to set the rails_env unless you are in production (the default) otherwise it will not work.
Restart nginx and with any luck you'll be able to access your application.
I made a few missteps doing my installation - such as thinking I needed to install nginx myself - but overall this went very smoothly.

Sorting ASP.NET GridView Control using JQuery Tablesorter Plugin

Displaying records in a tabular format is very common functionality of modern websites. Almost all the websites you visit these days have data to display in a table or datagrid and most of them also required the functionality of sorting records based on any column. Last week I had a chance to work with one of a popular JQuery plugin called Tablesorter and I was so impressed that I decided to write a full tutorial on it. In this tutorial, I will show you how you can use JQuery Tablesorter plugin with ASP.NET GridView control to provide client side sorting functionality to your site visitors.
Sorting ASP.NET GridView Control with JQuery Tablesorter Plugin
If you want to play with the Tablesorter JQuery plugin yourself with all the customized options, make sure you download the latest version ofTablesorter plugin from the following URL.
http://tablesorter.com/docs
Create a new ASP.NET website and drag a GridView control on the page. Disable the automatic columns generation by usingAutoGenerateColumns property and add some bound fields inside the GridView Columns collection. For this tutorial, make sure your GridView control HTML markup looks similar to the following:
<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333"
GridLines="Horizontal" Font-Size="9pt" Font-Names="Arial"
AutoGenerateColumns="False" BorderColor="#dadada"
BorderStyle="Solid" BorderWidth="1px">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID"
ItemStyle-Width="40" />
<asp:BoundField DataField="Name" HeaderText="Name"
ItemStyle-Width="80" />
<asp:BoundField DataField="Fee" DataFormatString="{0:n0}" HeaderText="Fee"
ItemStyle-Width="60" />
<asp:BoundField DataField="Price" DataFormatString="{0:c}"
HeaderText="Price" ItemStyle-Width="60" />
<asp:BoundField DataField="Discount" DataFormatString="{0:p1}"
HeaderText="Discount" ItemStyle-Width="70" />
<asp:BoundField DataField="Difference" DataFormatString="{0:n1}"
HeaderText="Difference" ItemStyle-Width="80" />
<asp:BoundField DataField="Date" DataFormatString="{0:MMM dd, yyyy}"
HeaderText="Date" ItemStyle-Width="100" />
<asp:BoundField DataField="OnSale" HeaderText="OnSale"
ItemStyle-Width="60" />
</Columns>
</asp:GridView>
As you can see bound fields are bound with columns such as ID, Name, Fee and so on. These columns are coming from a temporary DataTable object which I have filled and bind with GridView in the Page Load event. Following code shows the Page Load event and the code required to fill DataTable.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindData();
}
}
private void BindData()
{
int[] ids = {12, 13, 14, 15, 16};
string[] names = {"Alice", "James", "Peter", "Simon", "David"};
int[] fee = { 2299, 5123, 7564, 9595, 1600 };
decimal[] prices = { 12.99m, 122.23m, 25.64m, 66.85m, 1.60m };
decimal[] discounts = { 0.2m, 0.194m, 0.4564m, 0.209m, 0.310m };
decimal[] differences = { -12m, 19.4m, -45.64m, 200.9m, 41.60m };
string[] dates = { "04-12-2010", "07-23-2010", "07-14-2009", "12-12-2010", "11-03-2019" };
bool[] onSale = { true, false, true, true, false };
DataTable table = new DataTable();
table.Columns.Add("ID", typeof(System.Int32));
table.Columns.Add("Name", typeof(System.String));
table.Columns.Add("Fee", typeof(System.Decimal));
table.Columns.Add("Price", typeof(System.Decimal));
table.Columns.Add("Discount", typeof(System.Decimal));
table.Columns.Add("Difference", typeof(System.Int32));
table.Columns.Add("Date", typeof(System.DateTime));
table.Columns.Add("OnSale", typeof(System.Boolean));
for (int i = 0; i < 5; i++)
{
DataRow row = table.NewRow();
row["ID"] = ids[i];
row["Name"] = names[i];
row["Fee"] = fee[i];
row["Price"] = prices[i];
row["Discount"] = discounts[i];
row["Difference"] = differences[i];
row["Date"] = DateTime.Parse(dates[i]);
row["OnSale"] = onSale[i];
table.Rows.Add(row);
}
GridView1.DataSource = table;
GridView1.DataBind();
GridView1.UseAccessibleHeader = true;
GridView1.HeaderRow.TableSection = TableRowSection.TableHeader;
}

Before you build and test your web page, add the following CSS styles inside page head section to add some spice to your GridView.
<style type="text/css">
th
{
cursor:pointer;
background-color:#dadada;
color:Black;
font-weight:bold;
text-align:left;
}
th.headerSortUp
{
background-image: url(images/asc.gif);
background-position: right center;
background-repeat:no-repeat;
}
th.headerSortDown
{
background-image: url(images/desc.gif);
background-position: right center;
background-repeat:no-repeat;
}
td
{
border-bottom: solid 1px #dadada;
}
</style>

Add the following JQuery and Tablesorter javascript files references inside page head section.
<script src="scripts/jquery-1.4.3.min.js" type="text/javascript"></script>
<script src="scripts/jquery.tablesorter.min.js" type="text/javascript"></script>
Click here for table sorter plugin
Finally call the tablesorter function on GridView to make your GridVeiw sortable.
<script type="text/javascript">
$(document).ready(function() {
$("#GridView1").tablesorter();
});
</script>

You can see how easy is to add client side sorting functionality to your GridView using the Tablesorter plugin. You just need to call a single function Tablesorter to implement basic sorting. However, there are many other options to customize the sorting functionality, and I will recommend you to visit the Tablesorter plugin home page to read the documentation for all the available options.

Generate unique random string with desired length using GUID

GUID, also known as Globally Unique Identifier, is an 128-bit integer (16 bytes) that can be used to uniquely identify a record in the database (other than the auto-increase number). It is best used as a primary key as well.
But in some occasion, what you need is not really a GUID, but a random string that is "unique enough" to be used by your system. And you might want to store it as a string in your database (for whatever reason).
In C#, you can do this by using the GUID hash code. Here is the function that returns a "unique enough" string with a desired length:

        /// <summary>         
        /// Gets a unqiue key based on GUID string hash code.
        /// </summary>
         /// <param name="length">The length of the key returned.</param>
         /// <returns>Unique string</returns>
         private static string GetUniqueString(int length)
         {
             StringBuilder uniqHashKey = new StringBuilder();
             while (uniqHashKey.Length < length)
             {
                 // Get the GUID.
                 uniqHashKey.Append(Guid.NewGuid().ToString().GetHashCode().ToString("x"));
             }
             return uniqHashKey.ToString();
         }

Encrypting and Decrypting Query Strings in asp.net

Introduction

We often pass values between pages in the form of a query string as key-value pairs. Query string is the easiest way and most widely practiced mechanism of transferring small pieces of data between web pages. The end-user may change the value in the query string to play around with the application, and at the same time, it leads to compromising the security and data integrity of the system. So the solution is encrypting the query strings.

Following is the simple way of encryption and decryption mechanism in asp.net

First I created two methods for encryption and decryption

Encrypt the string

        private string Encrypt(string stringToEncrypt)
         {
             byte[] inputByteArray = Encoding.UTF8.GetBytes(stringToEncrypt);
             byte[] rgbIV = { 0x21, 0x43, 0x56, 0x87, 0x10, 0xfd, 0xea, 0x1c };
             byte[] key = { };
             try
             {
                 key = System.Text.Encoding.UTF8.GetBytes("A0D1nX0Q");
                 DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                 MemoryStream ms = new MemoryStream();
                 CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(key, rgbIV), CryptoStreamMode.Write);
                 cs.Write(inputByteArray, 0, inputByteArray.Length);
                 cs.FlushFinalBlock();
                 return Convert.ToBase64String(ms.ToArray());
             }
             catch (Exception e)
             {
                 return e.Message;
             }
         }         

Decrypt the encrypted string





        private string Decrypt(string EncryptedText)
{
byte[] inputByteArray = new byte[EncryptedText.Length + 1];
byte[] rgbIV = { 0x21, 0x43, 0x56, 0x87, 0x10, 0xfd, 0xea, 0x1c };
byte[] key = { };

try
{
key = System.Text.Encoding.UTF8.GetBytes("A0D1nX0Q");
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
inputByteArray = Convert.FromBase64String(EncryptedText);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(key, rgbIV), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
System.Text.Encoding encoding = System.Text.Encoding.UTF8;
return encoding.GetString(ms.ToArray());
}
catch (Exception e)
{
return e.Message;
}
}

It is better practice to encode the encrypted string before adding it to the URL like following, you can pass any number of parameters as you can (ex: OrderId=1&Name=RV )





   var addressLink = "http://abcxyz.com/abc.aspx?" + HttpUtility.UrlEncode(Encrypt(string.Format("OrderId={0}", orderId)));

Encryption is done, now we have to decrypt the encrypted string whenever we need, like following





   string str = "";
str = Request.RawUrl;
   var qs = Decrypt(HttpUtility.UrlDecode(str.Substring(strReq.IndexOf('?') + 1)));

Parse the returned string according to the parameters you have passed in above expression.

.NET interview Question for Fresher

Questions : 1
What is Code Access Security (CAS)? How does CAS work?

Answers : 1

CAS is the part of the .NET security model that determines whether or not a piece of code is allowed to run, and what resources it can use when it is running. For example, it is CAS that will prevent a .NET web applet from formatting your hard disk.

The CAS security policy revolves around two key concepts - code groups and permissions. Each .NET assembly is a member of a particular code group, and each code group is granted the permissions specified in a named permission set. For example, using the default security policy, a control downloaded from a web site belongs to the 'Zone - Internet' code group, which adheres to the permissions defined by the 'Internet' named permission set. (Naturally the 'Internet' named permission set represents a very restrictive range of permissions.)

Questions : 2
What are object pooling and connection pooling and difference? Where do we set the Min and Max Pool size for connection pooling?

Answers : 2

Object pooling is a COM+ service that enables you to reduce the overhead of creating each object from scratch. When an object is activated, it is pulled from the pool. When the object is deactivated, it is placed back into the pool to await the next request. You can configure object pooling by applying the ObjectPoolingAttribute attribute to a class that derives from the System.EnterpriseServices.ServicedComponent class. Object pooling lets you control the number of connections you use, as opposed to connection pooling, where you control the maximum number reached.

Following are important differences between object pooling and connection pooling:

1. Creation. When using connection pooling, creation is on the same thread, so if there is nothing in the pool, a connection is created on your behalf. With object pooling, the pool might decide to create a new object. However, if you have already reached your maximum, it instead gives you the next available object. This is crucial behavior when it takes a long time to create an object, but you do not use it for very long.

2. Enforcement of minimums and maximums. This is not done in connection pooling. The maximum value in object pooling is very important when trying to scale your application. You might need to multiplex thousands of requests to just a few objects. (TPC/C benchmarks rely on this.)

COM+ object pooling is identical to what is used in .NET Framework managed SQL Client connection pooling. For example, creation is on a different thread and minimums and maximums are enforced.

Questions : 3
What is a WebService and what is the underlying protocol used in it? Namespace?

Answers : 3

Web Services are applications delivered as a service on the Web. Web services allow for programmatic access of business logic over the Web. Web services typically rely on XML-based protocols, messages, and interface descriptions for communication and access. Web services are designed to be used by other programs or applications rather than directly by end user. Programs invoking a Web service are called clients. SOAP over HTTP is the most commonly used protocol for invoking Web services.

Questions : 4
What is serialization in .NET? What are the ways to control serialization?

Answers : 4

Serialization is the process of converting an object into a stream of bytes. Deserialization is the opposite process of creating an object from a stream of bytes. Serialization/Deserialization is mostly used to transport objects (e.g. during remoting), or to persist objects (e.g. to a file or database).Serialization can be defined as the process of storing the state of an object to a storage medium. During this process, the public and private fields of the object and the name of the class, including the assembly containing the class, are converted to a stream of bytes, which is then written to a data stream. When the object is subsequently deserialized, an exact clone of the original object is created.

1. Binary serialization preserves type fidelity, which is useful for preserving the state of an object between different invocations of an application. For example, you can share an object between different applications by serializing it to the clipboard. You can serialize an object to a stream, disk, memory, over the network, and so forth. Remoting uses serialization to pass objects "by value" from one computer or application domain to another.

2. XML serialization serializes only public properties and fields and does not preserve type fidelity. This is useful when you want to provide or consume data without restricting the application that uses the data. Because XML is an open standard, it is an attractive choice for sharing data across the Web. SOAP is an open standard, which makes it an attractive choice.

Questions : 5
Explain SOAP, WSDL, UDDI in brief.Namespace?

Answers : 5

SOAP:-SOAP is an XML-based messaging framework specifically designed for exchanging formatted data across the Internet, for example using request and reply messages or sending entire documents. SOAP is simple, easy to use, and completely neutral with respect to operating system, programming language, or distributed computing platform.After SOAP became available as a mechanism for exchanging XML messages among enterprises (or among disparate applications within the same enterprise), a better way was needed to describe the messages and how they are exchanged.

WSDL :-The Web Services Description Language (WSDL) is a particular form of an XML Schema, developed by Microsoft and IBM for the purpose of defining the XML message, operation, and protocol mapping of a web service accessed using SOAP or other XML protocol. WSDL defines web services in terms of "endpoints" that operate on XML messages. The WSDL syntax allows both the messages and the operations on the messages to be defined abstractly, so they can be mapped to multiple physical implementations. The current WSDL spec describes how to map messages and operations to SOAP 1.1, HTTP GET/POST, and MIME. WSDL creates web service definitions by mapping a group of endpoints into a logical sequence of operations on XML messages. The same XML message can be mapped to multiple operations (or services) and bound to one or more communications protocols (using "ports").

UDDI :-The Universal Description, Discovery, and Integration (UDDI) framework defines a data model (in XML) and SOAP APIs for registration and searches on business information, including the web services a business exposes to the Internet. UDDI is an independent consortium of vendors, founded by Microsoft, IBM, and Ariba, for the purpose of developing an Internet standard for web service description registration and discovery. Microsoft, IBM, and Ariba also are hosting the initial deployment of a UDDI service, which is conceptually patterned after DNS (the Internet service that translates URLs into TCP addresses). UDDI uses a private agreement profile of SOAP (i.e. UDDI doesn't use the SOAP serialization format because it's not well suited to passing complete XML documents (it's aimed at RPC style interactions). The main idea is that businesses use the SOAP APIs to register themselves with UDDI, and other businesses search UDDI when they want to discover a trading partner, for example someone from whom they wish to procure sheet metal, bolts, or transistors. The information in UDDI is categorized according to industry type and geographical location, allowing UDDI consumers to search through lists of potentially matching businesses to find the specific one they want to contact. Once a specific business is chosen, another call to UDDI is made to obtain the specific contact information for that business. The contact information includes a pointer to the target business's WSDL or other XML schema file describing the web service that the target business publishes. .

Questions : 6
What is Method Overriding? How to override a function in C#?

Answers : 6

An override method provides a new implementation of a member inherited from a base class. The method overridden by an override declaration is known as the overridden base method. The overridden base method must have the same signature as the override method.

Use the override modifier to modify a method, a property, an indexer, or an event. You cannot override a non-virtual or static method. The overridden base method must be virtual, abstract, or override.

Questions : 7
7. How can we check if all validation and controls are valid or proper?How can we force to run all validation control to run?

Answers : 7

By using Page.IsValid() property we can check if all validation and controls are valid or proper by using Page.Validate we can force to run all validation control to run

Questions : 8
What is the difference between Server.Transfer and Response.Redirect? Why would I choose one over the other?

Answers : 8

Server.Transfer transfers page processing from one page directly to the next page without making a round-trip back to the client's browser. This provides a faster response with a little less overhead on the server. Server.Transfer does not update the clients url history list or current url. Response.Redirect is used to redirect the user's browser to another page or site. This performas a trip back to the client where the client's browser is redirected to the new page. The user's browser history list is updated to reflect the new address.

Questions : 9
What is JIT (just in time)? how it works?

Answers : 9

Before Microsoft intermediate language (MSIL) can be executed, it must be converted by a .NET Framework just-in-time (JIT) compiler to native code, which is CPU-specific code that runs on the same computer architecture as the JIT compiler. Rather than using time and memory to convert all the MSIL in a portable executable (PE) file to native code, it converts the MSIL as it is needed during execution and stores the resulting native code so that it is accessible for subsequent calls. The runtime supplies another mode of compilation called install-time code generation. The install-time code generation mode converts MSIL to native code just as the regular JIT compiler does, but it converts larger units of code at a time, storing the resulting native code for use when the assembly is subsequently loaded and executed. As part of compiling MSIL to native code, code must pass a verification process unless an administrator has established a security policy that allows code to bypass verification. Verification examines MSIL and metadata to find out whether the code can be determined to be type safe, which means that it is known to access only the memory locations it is authorized to access.

Questions : 10
Difference between DataReader and DataAdapter / DataSet and DataAdapter?

Answers : 10

You can use the ADO.NET DataReader to retrieve a read-only, forward-only stream of data from a database. Using the DataReader can increase application performance and reduce system overhead because only one row at a time is ever in memory. After creating an instance of the Command object, you create a DataReader by calling Command.ExecuteReader to retrieve rows from a data source, as shown in the following example. SqlDataReader myReader = myCommand.ExecuteReader(); You use the Read method of the DataReader object to obtain a row from the results of the query. while (myReader.Read()) Console.WriteLine("\t{0}\t{1}", myReader.GetInt32(0), myReader.GetString(1)); myReader.Close(); The DataSet is a memory-resident representation of data that provides a consistent relational programming model regardless of the data source. It can be used with multiple and differing data sources, used with XML data, or used to manage data local to the application. The DataSet represents a complete set of data including related tables, constraints, and relationships among the tables. The methods and objects in a DataSet are consistent with those in the relational database model. The DataSet can also persist and reload its contents as XML and its schema as XML Schema definition language (XSD) schema. The DataAdapter serves as a bridge between a DataSet and a data source for retrieving and saving data. The DataAdapter provides this bridge by mapping Fill, which changes the data in the DataSet to match the data in the data source, and Update, which changes the data in the data source to match the data in the DataSet. If you are connecting to a Microsoft SQL Server database, you can increase overall performance by using the SqlDataAdapter along with its associated SqlCommand and SqlConnection. For other OLE DB-supported databases, use the DataAdapter with its associated OleDbCommand and OleDbConnection objects.

Questions : 11
Differences between dataset.clone and dataset.copy?

Answers : 11

Clone - Copies the structure of the DataSet, including all DataTable schemas, relations, and constraints. Does not copy any data.
Copy - Copies both the structure and data for this DataSet.

Questions : 12
What is State Management in .Net and how many ways are there to maintain a state in .Net? What is view state?

Answers : 12

Web pages are recreated each time the page is posted to the server. In traditional Web programming, this would ordinarily mean that all information associated with the page and the controls on the page would be lost with each round trip. To overcome this inherent limitation of traditional Web programming, the ASP.NET page framework includes various options to help you preserve changes — that is, for managing state. The page framework includes a facility called view state that automatically preserves property values of the page and all the controls on it between round trips. However, you will probably also have application-specific values that you want to preserve. To do so, you can use one of the state management options.
Client-Based State Management Options:
View State
Hidden Form Fields
Cookies
Query Strings
Server-Based State Management Options
Application State
Session State
Database Support

Questions : 13
Difference between web services & remoting? Namespace?

Answers : 13

ASP.NET Web Services .NET Remoting Protocol Can be accessed only over HTTP Can be accessed over any protocol (including TCP, HTTP, SMTP and so on) State Management Web services work in a stateless environment Provide support for both stateful and stateless environments through Singleton and SingleCall objects Type System Web services support only the datatypes defined in the XSD type system, limiting the number of objects that can be serialized. Using binary communication, .NET Remoting can provide support for rich type system Interoperability Web services support interoperability across platforms, and are ideal for heterogeneous environments. .NET remoting requires the client be built using .NET, enforcing homogenous environment. Reliability Highly reliable due to the fact that Web services are always hosted in IIS Can also take advantage of IIS for fault isolation. If IIS is not used, application needs to provide plumbing for ensuring the reliability of the application. Extensibility Provides extensibility by allowing us to intercept the SOAP messages during the serialization and deserialization stages. Very extensible by allowing us to customize the different components of the .NET remoting framework. Ease-of-Programming Easy-to-create and deploy. Complex to program.

Questions : 14
What is MSIL, IL?

Answers : 14

When compiling to managed code, the compiler translates your source code into Microsoft intermediate language (MSIL), which is a CPU-independent set of instructions that can be efficiently converted to native code. MSIL includes instructions for loading, storing, initializing, and calling methods on objects, as well as instructions for arithmetic and logical operations, control flow, direct memory access, exception handling, and other operations. Microsoft intermediate language (MSIL) is a language used as the output of a number of compilers and as the input to a just-in-time (JIT) compiler. The common language runtime includes a JIT compiler for converting MSIL to native code.

Questions : 15
What is strong name?

Answers : 15

A name that consists of an assembly's identity—its simple text name, version number, and culture information (if provided)—strengthened by a public key and a digital signature generated over the assembly.

Questions : 16
What is exception handling?

Answers : 16

When an exception occurs, the system searches for the nearest catch clause that can handle the exception, as determined by the run-time type of the exception. First, the current method is searched for a lexically enclosing try statement, and the associated catch clauses of the try statement are considered in order. If that fails, the method that called the current method is searched for a lexically enclosing try statement that encloses the point of the call to the current method. This search continues until a catch clause is found that can handle the current exception, by naming an exception class that is of the same class, or a base class, of the run-time type of the exception being thrown. A catch clause that doesn't name an exception class can handle any exception. Once a matching catch clause is found, the system prepares to transfer control to the first statement of the catch clause. Before execution of the catch clause begins, the system first executes, in order, any finally clauses that were associated with try statements more nested that than the one that caught the exception.

Exceptions that occur during destructor execution are worth special mention. If an exception occurs during destructor execution, and that exception is not caught, then the execution of that destructor is terminated and the destructor of the base class (if any) is called. If there is no base class (as in the case of the object type) or if there is no base class destructor, then the exception is discarded.

Questions : 17
What is the managed and unmanaged code in .net?

Answers : 17

The .NET Framework provides a run-time environment called the Common Language Runtime, which manages the execution of code and provides services that make the development process easier. Compilers and tools expose the runtime's functionality and enable you to write code that benefits from this managed execution environment. Code that you develop with a language compiler that targets the runtime is called managed code; it benefits from features such as cross-language integration, cross-language exception handling, enhanced security, versioning and deployment support, a simplified model for component interaction, and debugging and profiling services.

Questions : 18
What is the namespace threading in .net?

Answers : 18

System.Threading.Thread How to encode string string ss="pervej"; string encode=Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(ss)); Response.Write(encode);

Basic .NET, ASP.NET, OOPS and SQL Server Interview questions and answers.

  • What is IL code, CLR, CTS, GAC & GC?
  • How can we do Assembly versioning?
  • can you explain how ASP.NET application life cycle and page life cycle events fire?
  • What is the problem with Functional Programming?
  • Can you define OOP and the 4 principles of OOP?
  • What are Classes and Objects?
  • What is Inheritance?
  • What is Polymorphism, overloading, overriding and virtual?
  • Can you explain encapsulation and abstraction?
  • What is an abstract class?
  • Define Interface & What is the diff. between abstract & interface?
  • What problem does Delegate Solve ?
  • What is a Multicast delegate ?
  • What are events and what's the difference between delegates and events?
  • How can we make Asynchronous method calls using delegates ?
  • What is a stack, Heap, Value types and Reference types ?
  • What is boxing and unboxing ?
  • Can you explain ASP.NET application and Page life cycle ?
  • What is Authentication, Authorization, Principal & Identity objects?
  • How can we do Inproc and outProc session management ?
  • How can we windows , forms and passport authentication and authorization in ASP.NET ?
  • In a parent child relationship which constructor fires first ?

MVC ASP.NET Q & A series

  • How to create a simple "Hello World" using ASP.NET MVC template?
  • How to pass data from controller to views?
  • Can we see a simple sample of model using MVC template?
  • How can we create simple input screens using MVC template?
  • How can we create MVC views faster and make them strong typed by using HTML helper?
  • Can we see how easy it is do unit testing for MVC application?
  • What is MVC routing?
  • How can we set default values & validate MVC routes?
  • How we can define actions & navigate from one page to other page?

WCF, WPF, Silverlight, LINQ, Azure and EF 4.0 interview question and answers

  • What is SOA, Services and Messages ?
  • What is the difference between Service and Component?
  • What are basic steps to create a WCF service ?
  • What are endpoints, address, contracts and bindings?
  • What are various ways of hosting WCF service?
  • What is the difference of hosting a WCF service on IIS and Self hosting?
  • What is the difference between BasicHttpBinding and WsHttpBinding?
  • How can we do debugging and tracing in WCF?
  • Can you explain transactions in WCF (theory)?
  • How can we self host WCF service ?
  • What are the different ways of implementing WCF Security?
  • How can we implement SSL security on WCF(Transport Security)?
  • How can we implement transport security plus message security in WCF ?
  • How can we do WCF instancing ?
  • How Can we do WCF Concurency and throttling?
  • Can you explain the architecture of Silverlight ?
  • What are the basic things needed to make a silverlight application ?
  • How can we do transformations in SilverLight ?
  • Can you explain animation fundamentals in SilverLight?
  • What are the different layout methodologies in SilverLight?
  • Can you explain one way , two way and one time bindings?
  • How can we consume WCF service in SilverLight?
  • How can we connect databases using SilverLight?
  • What is LINQ and can you explain same with example?
  • Can you explain a simple example of LINQ to SQL?
  • How can we define relationships using LINQ to SQL?
  • How can we optimize LINQ relationships queries using ‘DataLoadOptions’?
  • Can we see a simple example of how we can do CRUD using LINQ to SQL?
  • How can we call a stored procedure using LINQ?
  • What is the need of WPF when we had GDI, GDI+ and DirectX?
  • Can you explain how we can make a simple WPF application?
  • Can you explain the three rendering modes i.e. Tier 0 , Tier 1 and Tier 2?
  • Can you explain the Architecture of WPF?
  • What is Azure?
  • Can you explain Azure Costing?
  • Can we see a simple Azure sample program?
  • What are the different steps to create a simple Worker application?
  • Can we understand Blobs in steps, Tables & Queues ?
  • Can we see a simple example for Azure tables?
  • What is Package and One click deploy(Deployment Part - 1) ?
  • What is Web.config transformation (Deployment Part-2)?
  • What is MEF and how can we implement the same?
  • How is MEF different from DIIOC?
  • Can you show us a simple implementation of MEF in Silverlight ?

Remove Hyperlink from ASP.NET TreeView Control Nodes

A simple post on how to change the TreeView node property to plain text instead of hyperlinks.

ASP.NET Tree view control rendered as HTML Table – TR –TD  elements. Each of the node are been represented as hyperlinks. Some times you may not want that fields as hyperlink and you want to be those nodes should be represent as static text. Many of the developer did the same using  font style or css style change of the node, but it can be done very easily.  In this small blog  post I am going to describe how you can represent a tree view node as simple text instead of hyperlink.

This can be done very easily using Tree Nodes, SelectionAction properties. SelectionAction having 4 different values, they are.

3

Select is the default option which marked node as hyperlinked and on selection of the node, it raised SelectedNodeChanged event.  For Expand Option, TreeNodeExpanded event will be raised while expanding the node. “SelectExpand” raised both the SelectedNodeChanged and  TreeNodeExpanded  events. Now if you don’t want to make the node as simple text, just change the SelectionAction properties to “None”.

1

Changing the SelectAction Dynamically

Above image showing how you can change the “SelectionAction” properties while creating a TreeView manually. But most of the time bind the data from a data source with tree view dynamically, for that you can use bellow code snippet.

2

So, what does this “Select” and “None” really make change internally ? Yes, when you are using Selection Action as “Select” Treeview Nodes rendered as HTML hyperlink in UI but for the “None” it rendered as "Span

Below image showing the “Span” element of TreeNode for “SelectionAction=”None””

4

Below image showing the hyperlink mode of TreeNode for “SelectionAction=”Select””

5

Creating a Data Access Layer (C#)

Introduction

As web developers, our lives revolve around working with data. We create databases to store the data, code to retrieve and modify it, and web pages to collect and summarize it. This is the first tutorial in a lengthy series that will explore techniques for implementing these common patterns in ASP.NET 2.0. We'll start with creating a software architecture composed of a Data Access Layer (DAL) using Typed DataSets, a Business Logic Layer (BLL) that enforces custom business rules, and a presentation layer composed of ASP.NET pages that share a common page layout. Once this backend groundwork has been laid, we'll move into reporting, showing how to display, summarize, collect, and validate data from a web application. These tutorials are geared to be concise and provide step-by-step instructions with plenty of screen shots to walk you through the process visually. Each tutorial is available in C# and Visual Basic versions and includes a download of the complete code used. (This first tutorial is quite lengthy, but the rest are presented in much more digestible chunks.)

For these tutorials we'll be using a Microsoft SQL Server 2005 Express Edition version of the Northwind database placed in the App_Data directory. In addition to the database file, the App_Data folder also contains the SQL scripts for creating the database, in case you want to use a different database version. These scripts can be also bedownloaded directly from Microsoft, if you'd prefer. If you use a different SQL Server version of the Northwind database, you will need to update the NORTHWNDConnectionString setting in the application's Web.config file. The web application was built using Visual Studio 2005 Professional Edition as a file system-based Web site project. However, all of the tutorials will work equally well with the free version of Visual Studio 2005, Visual Web Developer.
In this tutorial we'll start from the very beginning and create the Data Access Layer (DAL), followed by creating the Business Logic Layer (BLL) in the second tutorial, and working on page layout and navigation in the third. The tutorials after the third one will build upon the foundation laid in the first three. We've got a lot to cover in this first tutorial, so fire up Visual Studio and let's get started!

Step 1: Creating a Web Project and Connecting to the Database

Before we can create our Data Access Layer (DAL), we first need to create a web site and setup our database. Start by creating a new file system-based ASP.NET web site. To accomplish this, go to the File menu and choose New Web Site, displaying the New Web Site dialog box. Choose the ASP.NET Web Site template, set the Location drop-down list to File System, choose a folder to place the web site, and set the language to C#.

Create a New File System-Based Web Site

Figure 1: Create a New File System-Based Web Site

This will create a new web site with a Default.aspx ASP.NET page and an App_Data folder.

With the web site created, the next step is to add a reference to the database in Visual Studio's Server Explorer. By adding a database to the Server Explorer you can add tables, stored procedures, views, and so on all from within Visual Studio. You can also view table data or create your own queries either by hand or graphically via the Query Builder. Furthermore, when we build the Typed DataSets for the DAL we'll need to point Visual Studio to the database from which the Typed DataSets should be constructed. While we can provide this connection information at that point in time, Visual Studio automatically populates a drop-down list of the databases already registered in the Server Explorer.

The steps for adding the Northwind database to the Server Explorer depend on whether you want to use the SQL Server 2005 Express Edition database in the App_Data folder or if you have a Microsoft SQL Server 2000 or 2005 database server setup that you want to use instead.

Using a Database in the App_Data Folder

If you do not have a SQL Server 2000 or 2005 database server to connect to, or you simply want to avoid having to add the database to a database server, you can use the SQL Server 2005 Express Edition version of the Northwind database that is located in the downloaded website's App_Data folder (NORTHWND.MDF).

A database placed in the App_Data folder is automatically added to the Server Explorer. Assuming you have SQL Server 2005 Express Edition installed on your machine you should see a node named NORTHWND.MDF in the Server Explorer, which you can expand and explore its tables, views, stored procedure, and so on (see Figure 2).

The App_Data folder can also hold Microsoft Access .mdb files, which, like their SQL Server counterparts, are automatically added to the Server Explorer. If you don't want to use any of the SQL Server options, you can alwaysdownload a Microsoft Access version of the Northwind database file and drop into the App_Data directory. Keep in mind, however, that Access databases aren't as feature-rich as SQL Server, and aren't designed to be used in web site scenarios. Furthermore, a couple of the 35+ tutorials will utilize certain database-level features that aren't supported by Access.

Connecting to the Database in a Microsoft SQL Server 2000 or 2005 Database Server

Alternatively, you may connect to a Northwind database installed on a database server. If the database server does not already have the Northwind database installed, you first must add it to database server by running the installation script included in this tutorial's download or by downloading the SQL Server 2000 version of Northwind and installation script directly from Microsoft's web site.

Once you have the database installed, go to the Server Explorer in Visual Studio, right-click on the Data Connections node, and choose Add Connection. If you don't see the Server Explorer go to the View / Server Explorer, or hit Ctrl+Alt+S. This will bring up the Add Connection dialog box, where you can specify the server to connect to, the authentication information, and the database name. Once you have successfully configured the database connection information and clicked the OK button, the database will be added as a node underneath the Data Connections node. You can expand the database node to explore its tables, views, stored procedures, and so on.

Add a Connection to Your Database Server's Northwind Database

Figure 2: Add a Connection to Your Database Server's Northwind Database

Step 2: Creating the Data Access Layer

When working with data one option is to embed the data-specific logic directly into the presentation layer (in a web application, the ASP.NET pages make up the presentation layer). This may take the form of writing ADO.NET code in the ASP.NET page's code portion or using the SqlDataSource control from the markup portion. In either case, this approach tightly couples the data access logic with the presentation layer. The recommended approach, however, is to separate the data access logic from the presentation layer. This separate layer is referred to as the Data Access Layer, DAL for short, and is typically implemented as a separate Class Library project. The benefits of this layered architecture are well documented (see the "Further Readings" section at the end of this tutorial for information on these advantages) and is the approach we will take in this series.

All code that is specific to the underlying data source such as creating a connection to the database, issuingSELECT, INSERT, UPDATE, and DELETE commands, and so on should be located in the DAL. The presentation layer should not contain any references to such data access code, but should instead make calls into the DAL for any and all data requests. Data Access Layers typically contain methods for accessing the underlying database data. The Northwind database, for example, has Products and Categories tables that record the products for sale and the categories to which they belong. In our DAL we will have methods like:

  • GetCategories(), which will return information about all of the categories
  • GetProducts(), which will return information about all of the products
  • GetProductsByCategoryID(categoryID), which will return all products that belong to a specified category
  • GetProductByProductID(productID), which will return information about a particular product

These methods, when invoked, will connect to the database, issue the appropriate query, and return the results. How we return these results is important. These methods could simply return a DataSet or DataReader populated by the database query, but ideally these results should be returned using strongly-typed objects. A strongly-typed object is one whose schema is rigidly defined at compile time, whereas the opposite, a loosely-typed object, is one whose schema is not known until runtime.

For example, the DataReader and the DataSet (by default) are loosely-typed objects since their schema is defined by the columns returned by the database query used to populate them. To access a particular column from a loosely-typed DataTable we need to use syntax like: DataTable.Rows[index]["columnName"]. The DataTable's loose typing in this example is exhibited by the fact that we need to access the column name using a string or ordinal index. A strongly-typed DataTable, on the other hand, will have each of its columns implemented as properties, resulting in code that looks like: DataTable.Rows[index].columnName.

To return strongly-typed objects, developers can either create their own custom business objects or use Typed DataSets. A business object is implemented by the developer as a class whose properties typically reflect the columns of the underlying database table the business object represents. A Typed DataSet is a class generated for you by Visual Studio based on a database schema and whose members are strongly-typed according to this schema. The Typed DataSet itself consists of classes that extend the ADO.NET DataSet, DataTable, and DataRow classes. In addition to strongly-typed DataTables, Typed DataSets now also include TableAdapters, which are classes with methods for populating the DataSet's DataTables and propagating modifications within the DataTables back to the database.

Note: For more information on the advantages and disadvantages of using Typed DataSets versus custom business objects, refer to Designing Data Tier Components and Passing Data Through Tiers.

We'll use strongly-typed DataSets for these tutorials' architecture. Figure 3 illustrates the workflow between the different layers of an application that uses Typed DataSets.

All Data Access Code is Relegated to the DAL

Figure 3: All Data Access Code is Relegated to the DAL

Creating a Typed DataSet and Table Adapter

To begin creating our DAL, we start by adding a Typed DataSet to our project. To accomplish this, right-click on the project node in the Solution Explorer and choose Add a New Item. Select the DataSet option from the list of templates and name it Northwind.xsd.

Choose to Add a New DataSet to Your Project

Figure 4: Choose to Add a New DataSet to Your Project

After clicking Add, when prompted to add the DataSet to the App_Code folder, choose Yes. The Designer for the Typed DataSet will then be displayed, and the TableAdapter Configuration Wizard will start, allowing you to add your first TableAdapter to the Typed DataSet.

A Typed DataSet serves as a strongly-typed collection of data; it is composed of strongly-typed DataTable instances, each of which is in turn composed of strongly-typed DataRow instances. We will create a strongly-typed DataTable for each of the underlying database tables that we need to work with in this tutorials series. Let's start with creating a DataTable for the Products table.

Keep in mind that strongly-typed DataTables do not include any information on how to access data from their underlying database table. In order to retrieve the data to populate the DataTable, we use a TableAdapter class, which functions as our Data Access Layer. For our Products DataTable, the TableAdapter will contain the methodsGetProducts(), GetProductByCategoryID(categoryID), and so on that we'll invoke from the presentation layer. The DataTable's role is to serve as the strongly-typed objects used to pass data between the layers.

The TableAdapter Configuration Wizard begins by prompting you to select which database to work with. The drop-down list shows those databases in the Server Explorer. If you did not add the Northwind database to the Server Explorer, you can click the New Connection button at this time to do so.

Choose the Northwind Database from the Drop-Down List

Figure 5: Choose the Northwind Database from the Drop-Down List

After selecting the database and clicking Next, you'll be asked if you want to save the connection string in theWeb.config file. By saving the connection string you'll avoid having it hard coded in the TableAdapter classes, which simplifies things if the connection string information changes in the future. If you opt to save the connection string in the configuration file it's placed in the <connectionStrings> section, which can be optionally encrypted for improved security or modified later through the new ASP.NET 2.0 Property Page within the IIS GUI Admin Tool, which is more ideal for administrators.

Save the Connection String to Web.config

Figure 6: Save the Connection String to Web.config

Next, we need to define the schema for the first strongly-typed DataTable and provide the first method for our TableAdapter to use when populating the strongly-typed DataSet. These two steps are accomplished simultaneously by creating a query that returns the columns from the table that we want reflected in our DataTable. At the end of the wizard we'll give a method name to this query. Once that's been accomplished, this method can be invoked from our presentation layer. The method will execute the defined query and populate a strongly-typed DataTable.

To get started defining the SQL query we must first indicate how we want the TableAdapter to issue the query. We can use an ad-hoc SQL statement, create a new stored procedure, or use an existing stored procedure. For these tutorials we'll use ad-hoc SQL statements. Refer to Brian Noyes's article, Build a Data Access Layer with the Visual Studio 2005 DataSet Designer for an example of using stored procedures.

Query the Data Using an Ad-Hoc SQL Statement

Figure 7: Query the Data Using an Ad-Hoc SQL Statement

At this point we can type in the SQL query by hand. When creating the first method in the TableAdapter you typically want to have the query return those columns that need to be expressed in the corresponding DataTable. We can accomplish this by creating a query that returns all columns and all rows from the Products table:

Enter the SQL Query Into the Textbox

Figure 8: Enter the SQL Query Into the Textbox

Alternatively, use the Query Builder and graphically construct the query, as shown in Figure 9.

Create the Query Graphically, through the Query Editor

Figure 9: Create the Query Graphically, through the Query Editor

After creating the query, but before moving onto the next screen, click the Advanced Options button. In Web Site Projects, "Generate Insert, Update, and Delete statements" is the only advanced option selected by default; if you run this wizard from a Class Library or a Windows Project the "Use optimistic concurrency" option will also be selected. Leave the "Use optimistic concurrency" option unchecked for now. We'll examine optimistic concurrency in future tutorials.

Select Only the  Generate Insert, Update, and Delete statements  Option

Figure 10: Select Only the Generate Insert, Update, and Delete statements Option

After verifying the advanced options, click Next to proceed to the final screen. Here we are asked to select which methods to add to the TableAdapter. There are two patterns for populating data:

  • Fill a DataTable with this approach a method is created that takes in a DataTable as a parameter and populates it based on the results of the query. The ADO.NET DataAdapter class, for example, implements this pattern with its Fill() method.
  • Return a DataTable with this approach the method creates and fills the DataTable for you and returns it as the methods return value.

You can have the TableAdapter implement one or both of these patterns. You can also rename the methods provided here. Let's leave both checkboxes checked, even though we'll only be using the latter pattern throughout these tutorials. Also, let's rename the rather generic GetData method to GetProducts.

If checked, the final checkbox, "GenerateDBDirectMethods," creates Insert(), Update(), and Delete() methods for the TableAdapter. If you leave this option unchecked, all updates will need to be done through the TableAdapter's sole Update() method, which takes in the Typed DataSet, a DataTable, a single DataRow, or an array of DataRows. (If you've unchecked the "Generate Insert, Update, and Delete statements" option from the advanced properties in Figure 9 this checkbox's setting will have no effect.) Let's leave this checkbox selected.

Change the Method Name from GetData to GetProducts

Figure 11: Change the Method Name from GetData to GetProducts

Complete the wizard by clicking Finish. After the wizard closes we are returned to the DataSet Designer which shows the DataTable we just created. You can see the list of columns in the Products DataTable (ProductID,ProductName, and so on), as well as the methods of the ProductsTableAdapter (Fill() and GetProducts()).

The Products DataTable and ProductsTableAdapter have been Added to the Typed DataSet

Figure 12: The Products DataTable and ProductsTableAdapter have been Added to the Typed DataSet

At this point we have a Typed DataSet with a single DataTable (Northwind.Products) and a strongly-typed DataAdapter class (NorthwindTableAdapters.ProductsTableAdapter) with a GetProducts() method. These objects can be used to access a list of all products from code like:

NorthwindTableAdapters.ProductsTableAdapter productsAdapter =
new NorthwindTableAdapters.ProductsTableAdapter();
Northwind.ProductsDataTable products;
products = productsAdapter.GetProducts();
foreach (Northwind.ProductsRow productRow in products)
Response.Write("Product: " + productRow.ProductName + "<br />");

This code did not require us to write one bit of data access-specific code. We did not have to instantiate any ADO.NET classes, we didn't have to refer to any connection strings, SQL queries, or stored procedures. Instead, the TableAdapter provides the low-level data access code for us.

Each object used in this example is also strongly-typed, allowing Visual Studio to provide IntelliSense and compile-time type checking. And best of all the DataTables returned by the TableAdapter can be bound to ASP.NET data Web controls, such as the GridView, DetailsView, DropDownList, CheckBoxList, and several others. The following example illustrates binding the DataTable returned by the GetProducts() method to a GridView in just a scant three lines of code within the Page_Load event handler.

AllProducts.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="AllProducts.aspx.cs"
Inherits="AllProducts" %>
<!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>View All Products in a GridView</title>
<link href="Styles.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>
All Products</h2>
<p>
<asp:GridView ID="GridView1" runat="server"
CssClass="DataWebControlStyle">
<HeaderStyle CssClass="HeaderStyle" />
<AlternatingRowStyle CssClass="AlternatingRowStyle" />
</asp:GridView>
</p>
</div>
</form>
</body>
</html>

AllProducts.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using NorthwindTableAdapters;
public partial class AllProducts : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ProductsTableAdapter productsAdapter = new
ProductsTableAdapter();
GridView1.DataSource = productsAdapter.GetProducts();
GridView1.DataBind();
}
}

The List of Products is Displayed in a GridView

Figure 13: The List of Products is Displayed in a GridView

While this example required that we write three lines of code in our ASP.NET page's Page_Load event handler, in future tutorials we'll examine how to use the ObjectDataSource to declaratively retrieve the data from the DAL. With the ObjectDataSource we'll not have to write any code and will get paging and sorting support as well!

Step 3: Adding Parameterized Methods to the Data Access Layer

At this point our ProductsTableAdapter class has but one method, GetProducts(), which returns all of the products in the database. While being able to work with all products is definitely useful, there are times when we'll want to retrieve information about a specific product, or all products that belong to a particular category. To add such functionality to our Data Access Layer we can add parameterized methods to the TableAdapter.

Let's add the GetProductsByCategoryID(categoryID) method. To add a new method to the DAL, return to the DataSet Designer, right-click in the ProductsTableAdapter section, and choose Add Query.

Right-Click on the TableAdapter and Choose Add Query

Figure 14: Right-Click on the TableAdapter and Choose Add Query

We are first prompted about whether we want to access the database using an ad-hoc SQL statement or a new or existing stored procedure. Let's choose to use an ad-hoc SQL statement again. Next, we are asked what type of SQL query we'd like to use. Since we want to return all products that belong to a specified category, we want to write a SELECT statement which returns rows.

Choose to Create a SELECT Statement Which Returns Rows

Figure 15: Choose to Create a SELECT Statement Which Returns Rows

The next step is to define the SQL query used to access the data. Since we want to return only those products that belong to a particular category, I use the same SELECT statement from GetProducts(), but add the followingWHERE clause: WHERE CategoryID = @CategoryID. The @CategoryID parameter indicates to the TableAdapter wizard that the method we're creating will require an input parameter of the corresponding type (namely, a nullable integer).

Enter a Query to Only Return Products in a Specified Category

Figure 16: Enter a Query to Only Return Products in a Specified Category

In the final step we can choose which data access patterns to use, as well as customize the names of the methods generated. For the Fill pattern, let's change the name to FillByCategoryID and for the return a DataTable return pattern (the GetX methods), let's use GetProductsByCategoryID.

Choose the Names for the TableAdapter Methods

Figure 17: Choose the Names for the TableAdapter Methods

After completing the wizard, the DataSet Designer includes the new TableAdapter methods.

The Products Can Now be Queried by Category

Figure 18: The Products Can Now be Queried by Category

Take a moment to add a GetProductByProductID(productID) method using the same technique.

These parameterized queries can be tested directly from the DataSet Designer. Right-click on the method in the TableAdapter and choose Preview Data. Next, enter the values to use for the parameters and click Preview.

Those Products Belonging to the Beverages Category are Shown

Figure 19: Those Products Belonging to the Beverages Category are Shown

With the GetProductsByCategoryID(categoryID) method in our DAL, we can now create an ASP.NET page that displays only those products in a specified category. The following example shows all products that are in the Beverages category, which have a CategoryID of 1.

Beverages.asp

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Beverages.aspx.cs"
Inherits="Beverages" %>
<!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>Untitled Page</title>
<link href="Styles.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>Beverages</h2>
<p>
<asp:GridView ID="GridView1" runat="server"
CssClass="DataWebControlStyle">
<HeaderStyle CssClass="HeaderStyle" />
<AlternatingRowStyle CssClass="AlternatingRowStyle" />
</asp:GridView>
</p>
</div>
</form>
</body>
</html>

Beverages.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using NorthwindTableAdapters;
public partial class Beverages : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ProductsTableAdapter productsAdapter = new
ProductsTableAdapter();
GridView1.DataSource =
productsAdapter.GetProductsByCategoryID(1);
GridView1.DataBind();
}
}

Those Products in the Beverages Category are Displayed

Figure 20: Those Products in the Beverages Category are Displayed

Step 4: Inserting, Updating, and Deleting Data

There are two patterns commonly used for inserting, updating, and deleting data. The first pattern, which I'll call the database direct pattern, involves creating methods that, when invoked, issue an INSERT, UPDATE, or DELETEcommand to the database that operates on a single database record. Such methods are typically passed in a series of scalar values (integers, strings, Booleans, DateTimes, and so on) that correspond to the values to insert, update, or delete. For example, with this pattern for the Products table the delete method would take in an integer parameter, indicating the ProductID of the record to delete, while the insert method would take in a string for theProductName, a decimal for the UnitPrice, an integer for the UnitsOnStock, and so on.

Each Insert, Update, and Delete Request is Sent to the Database Immediately

Figure 21: Each Insert, Update, and Delete Request is Sent to the Database Immediately

The other pattern, which I'll refer to as the batch update pattern, is to update an entire DataSet, DataTable, or collection of DataRows in one method call. With this pattern a developer deletes, inserts, and modifies the DataRows in a DataTable and then passes those DataRows or DataTable into an update method. This method then enumerates the DataRows passed in, determines whether or not they've been modified, added, or deleted (via the DataRow's RowState property value), and issues the appropriate database request for each record.

All Changes are Synchronized with the Database When the Update Method is Invoked

Figure 22: All Changes are Synchronized with the Database When the Update Method is Invoked

The TableAdapter uses the batch update pattern by default, but also supports the DB direct pattern. Since we selected the "Generate Insert, Update, and Delete statements" option from the Advanced Properties when creating our TableAdapter, the ProductsTableAdapter contains an Update() method, which implements the batch update pattern. Specifically, the TableAdapter contains an Update() method that can be passed the Typed DataSet, a strongly-typed DataTable, or one or more DataRows. If you left the "GenerateDBDirectMethods" checkbox checked when first creating the TableAdapter the DB direct pattern will also be implemented via Insert(), Update(), andDelete() methods.

Both data modification patterns use the TableAdapter's InsertCommand, UpdateCommand, and DeleteCommandproperties to issue their INSERT, UPDATE, and DELETE commands to the database. You can inspect and modify the InsertCommand, UpdateCommand, and DeleteCommand properties by clicking on the TableAdapter in the DataSet Designer and then going to the Properties window. (Make sure you have selected the TableAdapter, and that the ProductsTableAdapter object is the one selected in the drop-down list in the Properties window.)

The TableAdapter has InsertCommand, UpdateCommand, and DeleteCommand Properties

Figure 23: The TableAdapter has InsertCommand, UpdateCommand, and DeleteCommand Properties

To examine or modify any of these database command properties, click on the CommandText subproperty, which will bring up the Query Builder.

Configure the INSERT, UPDATE, and DELETE Statements in the Query Builder

Figure 24: Configure the INSERT, UPDATE, and DELETE Statements in the Query Builder

The following code example shows how to use the batch update pattern to double the price of all products that are not discontinued and that have 25 units in stock or less:

NorthwindTableAdapters.ProductsTableAdapter productsAdapter =
new NorthwindTableAdapters.ProductsTableAdapter();
// For each product, double its price if it is not discontinued and
// there are 25 items in stock or less
Northwind.ProductsDataTable products = productsAdapter.GetProducts();
foreach (Northwind.ProductsRow product in products)
if (!product.Discontinued && product.UnitsInStock <= 25)
product.UnitPrice *= 2;
// Update the products
productsAdapter.Update(products);

The code below illustrates how to use the DB direct pattern to programmatically delete a particular product, then update one, and then add a new one:

NorthwindTableAdapters.ProductsTableAdapter productsAdapter =
new NorthwindTableAdapters.ProductsTableAdapter();
// Delete the product with ProductID 3
productsAdapter.Delete(3);
// Update Chai (ProductID of 1), setting the UnitsOnOrder to 15
productsAdapter.Update("Chai", 1, 1, "10 boxes x 20 bags",
18.0m, 39, 15, 10, false, 1);
// Add a new product
productsAdapter.Insert("New Product", 1, 1,
"12 tins per carton", 14.95m, 15, 0, 10, false);

Creating Custom Insert, Update, and Delete Methods

The Insert(), Update(), and Delete() methods created by the DB direct method can be a bit cumbersome, especially for tables with many columns. Looking at the previous code example, without IntelliSense's help it's not particularly clear what Products table column maps to each input parameter to the Update() and Insert() methods. There may be times when we only want to update a single column or two, or want a customized Insert() method that will, perhaps, return the value of the newly inserted record's IDENTITY (auto-increment) field.

To create such a custom method, return to the DataSet Designer. Right-click on the TableAdapter and choose Add Query, returning to the TableAdapter wizard. On the second screen we can indicate the type of query to create. Let's create a method that adds a new product and then returns the value of the newly added record's ProductID. Therefore, opt to create an INSERT query.

Create a Method to Add a New Row to the Products Table

Figure 25: Create a Method to Add a New Row to the Products Table

On the next screen the InsertCommand's CommandText appears. Augment this query by adding SELECT SCOPE_IDENTITY() at the end of the query, which will return the last identity value inserted into an IDENTITYcolumn in the same scope. (See the technical documentation for more information about SCOPE_IDENTITY() and why you probably want to use SCOPE_IDENTITY() in lieu of @@IDENTITY.) Make sure that you end the INSERTstatement with a semi-colon before adding the SELECT statement.

Augment the Query to Return the SCOPE_IDENTITY() Value

Figure 26: Augment the Query to Return the SCOPE_IDENTITY() Value

Finally, name the new method InsertProduct.

Set the New Method Name to InsertProduct

Figure 27: Set the New Method Name to InsertProduct

When you return to the DataSet Designer you'll see that the ProductsTableAdapter contains a new method,InsertProduct. If this new method doesn't have a parameter for each column in the Products table, chances are you forgot to terminate the INSERT statement with a semi-colon. Configure the InsertProduct method and ensure you have a semi-colon delimiting the INSERT and SELECT statements.

By default, insert methods issue non-query methods, meaning that they return the number of affected rows. However, we want the InsertProduct method to return the value returned by the query, not the number of rows affected. To accomplish this, adjust the InsertProduct method's ExecuteMode property to Scalar.

Change the ExecuteMode Property to Scalar

Figure 28: Change the ExecuteMode Property to Scalar

The following code shows this new InsertProduct method in action:

NorthwindTableAdapters.ProductsTableAdapter productsAdapter =
new NorthwindTableAdapters.ProductsTableAdapter();
// Add a new product
int new_productID = Convert.ToInt32(productsAdapter.InsertProduct
("New Product", 1, 1, "12 tins per carton", 14.95m, 10, 0, 10, false));
// On second thought, delete the product
productsAdapter.Delete(new_productID);

Step 5: Completing the Data Access Layer

Note that the ProductsTableAdapters class returns the CategoryID and SupplierID values from the Productstable, but doesn't include the CategoryName column from the Categories table or the CompanyName column from the Suppliers table, although these are likely the columns we want to display when showing product information. We can augment the TableAdapter's initial method, GetProducts(), to include both the CategoryNameand CompanyName column values, which will update the strongly-typed DataTable to include these new columns as well.

This can present a problem, however, as the TableAdapter's methods for inserting, updating, and deleting data are based off of this initial method. Fortunately, the auto-generated methods for inserting, updating, and deleting are not affected by subqueries in the SELECT clause. By taking care to add our queries to Categories and Suppliers as subqueries, rather than JOINs, we'll avoid having to rework those methods for modifying data. Right-click on theGetProducts() method in the ProductsTableAdapter and choose Configure. Then, adjust the SELECT clause so that it looks like:

SELECT ProductID, ProductName, SupplierID, CategoryID,
QuantityPerUnit, UnitPrice, UnitsInStock, UnitsOnOrder, ReorderLevel, Discontinued,
(SELECT CategoryName FROM Categories
WHERE Categories.CategoryID = Products.CategoryID) as CategoryName,
(SELECT CompanyName FROM Suppliers
WHERE Suppliers.SupplierID = Products.SupplierID) as SupplierName
FROM Products

Update the SELECT Statement for the GetProducts() Method

Figure 29: Update the SELECT Statement for the GetProducts() Method

After updating the GetProducts() method to use this new query the DataTable will include two new columns:CategoryName and SupplierName.

The Products DataTable has Two New Columns

Figure 30: The Products DataTable has Two New Columns

Take a moment to update the SELECT clause in the GetProductsByCategoryID(categoryID) method as well.

If you update the GetProducts() SELECT using JOIN syntax the DataSet Designer won't be able to auto-generate the methods for inserting, updating, and deleting database data using the DB direct pattern. Instead, you'll have to manually create them much like we did with the InsertProduct method earlier in this tutorial. Furthermore, you'll manually have to provide the InsertCommand, UpdateCommand, and DeleteCommand property values if you want to use the batch updating pattern.

Adding the Remaining TableAdapters

Up until now, we've only looked at working with a single TableAdapter for a single database table. However, the Northwind database contains several related tables that we'll need to work with in our web application. A Typed DataSet can contain multiple, related DataTables. Therefore, to complete our DAL we need to add DataTables for the other tables we'll be using in these tutorials. To add a new TableAdapter to a Typed DataSet, open the DataSet Designer, right-click in the Designer, and choose Add / TableAdapter. This will create a new DataTable and TableAdapter and walk you through the wizard we examined earlier in this tutorial.

Take a few minutes to create the following TableAdapters and methods using the following queries. Note that the queries in the ProductsTableAdapter include the subqueries to grab each product's category and supplier names. Additionally, if you've been following along, you've already added the ProductsTableAdapter class'sGetProducts() and GetProductsByCategoryID(categoryID) methods.

  • ProductsTableAdapter
    • GetProducts:
      SELECT ProductID, ProductName, SupplierID,
      CategoryID, QuantityPerUnit, UnitPrice, UnitsInStock,
      UnitsOnOrder, ReorderLevel, Discontinued
      ,
      (SELECT CategoryName FROM Categories WHERE
      Categories.CategoryID = Products.CategoryID) as
      CategoryName, (SELECT CompanyName FROM Suppliers
      WHERE Suppliers.SupplierID = Products.SupplierID)
      as SupplierName
      FROM Products
    • GetProductsByCategoryID:
      SELECT ProductID, ProductName, SupplierID, CategoryID,
      QuantityPerUnit, UnitPrice, UnitsInStock, UnitsOnOrder,
      ReorderLevel, Discontinued
      , (SELECT CategoryName
      FROM Categories WHERE Categories.CategoryID =
      Products.CategoryID) as CategoryName,
      (SELECT CompanyName FROM Suppliers WHERE
      Suppliers.SupplierID = Products.SupplierID)
      as SupplierName
      FROM Products
      WHERE CategoryID = @CategoryID
    • GetProductsBySupplierID:
      SELECT ProductID, ProductName, SupplierID, CategoryID,
      QuantityPerUnit, UnitPrice, UnitsInStock, UnitsOnOrder,
      ReorderLevel, Discontinued
      , (SELECT CategoryName
      FROM Categories WHERE Categories.CategoryID =
      Products.CategoryID) as CategoryName,
      (SELECT CompanyName FROM Suppliers WHERE
      Suppliers.SupplierID = Products.SupplierID) as SupplierName
      FROM Products
      WHERE SupplierID = @SupplierID
    • GetProductByProductID:
      SELECT ProductID, ProductName, SupplierID, CategoryID,
      QuantityPerUnit, UnitPrice, UnitsInStock, UnitsOnOrder,
      ReorderLevel, Discontinued
      , (SELECT CategoryName
      FROM Categories WHERE Categories.CategoryID =
      Products.CategoryID) as CategoryName,
      (SELECT CompanyName FROM Suppliers WHERE Suppliers.SupplierID = Products.SupplierID)
      as SupplierName
      FROM Products
      WHERE ProductID = @ProductID
  • CategoriesTableAdapter
    • GetCategories:
      SELECT CategoryID, CategoryName, Description
      FROM Categories
    • GetCategoryByCategoryID:
      SELECT CategoryID, CategoryName, Description
      FROM Categories
      WHERE CategoryID = @CategoryID
  • SuppliersTableAdapter
    • GetSuppliers:
      SELECT SupplierID, CompanyName, Address,
      City, Country, Phone
      FROM Suppliers
    • GetSuppliersByCountry:
      SELECT SupplierID, CompanyName, Address,
      City, Country, Phone
      FROM Suppliers
      WHERE Country = @Country
    • GetSupplierBySupplierID:
      SELECT SupplierID, CompanyName, Address,
      City, Country, Phone
      FROM Suppliers
      WHERE SupplierID = @SupplierID
  • EmployeesTableAdapter
    • GetEmployees:
      SELECT EmployeeID, LastName, FirstName, Title,
      HireDate, ReportsTo, Country
      FROM Employees
    • GetEmployeesByManager:
      SELECT EmployeeID, LastName, FirstName, Title,
      HireDate, ReportsTo, Country
      FROM Employees
      WHERE ReportsTo = @ManagerID
    • GetEmployeeByEmployeeID:
      SELECT EmployeeID, LastName, FirstName, Title,
      HireDate, ReportsTo, Country
      FROM Employees
      WHERE EmployeeID = @EmployeeID

The DataSet Designer After the Four TableAdapters Have Been Added

Figure 31: The DataSet Designer After the Four TableAdapters Have Been Added

Adding Custom Code to the DAL

The TableAdapters and DataTables added to the Typed DataSet are expressed as an XML Schema Definition file (Northwind.xsd). You can view this schema information by right-clicking on the Northwind.xsd file in the Solution Explorer and choosing View Code.

The XML Schema Definition (XSD) File for the Northwinds Typed DataSet

Figure 32: The XML Schema Definition (XSD) File for the Northwinds Typed DataSet

This schema information is translated into C# or Visual Basic code at design time when compiled or at runtime (if needed), at which point you can step through it with the debugger. To view this auto-generated code go to the Class View and drill down to the TableAdapter or Typed DataSet classes. If you don't see the Class View on your screen, go to the View menu and select it from there, or hit Ctrl+Shift+C. From the Class View you can see the properties, methods, and events of the Typed DataSet and TableAdapter classes. To view the code for a particular method, double-click the method name in the Class View or right-click on it and choose Go To Definition.

Inspect the Auto-Generated Code by Selecting Go To Definition from the Class View

Figure 33: Inspect the Auto-Generated Code by Selecting Go To Definition from the Class View

While auto-generated code can be a great time saver, the code is often very generic and needs to be customized to meet the unique needs of an application. The risk of extending auto-generated code, though, is that the tool that generated the code might decide it's time to "regenerate" and overwrite your customizations. With .NET 2.0's new partial class concept, it's easy to split a class across multiple files. This enables us to add our own methods, properties, and events to the auto-generated classes without having to worry about Visual Studio overwriting our customizations.

To demonstrate how to customize the DAL, let's add a GetProducts() method to the SuppliersRow class. TheSuppliersRow class represents a single record in the Suppliers table; each supplier can provider zero to many products, so GetProducts() will return those products of the specified supplier. To accomplish this create a new class file in the App_Code folder named SuppliersRow.cs and add the following code:

using System;
using System.Data;
using NorthwindTableAdapters;
public partial class Northwind
{
public partial class SuppliersRow
{
public Northwind.ProductsDataTable GetProducts()
{
ProductsTableAdapter productsAdapter =
new ProductsTableAdapter();
return
productsAdapter.GetProductsBySupplierID(this.SupplierID);
}
}
}

This partial class instructs the compiler that when building the Northwind.SuppliersRow class to include theGetProducts() method we just defined. If you build your project and then return to the Class View you'll seeGetProducts() now listed as a method of Northwind.SuppliersRow.

The GetProducts() Method is Now Part of the Northwind.SuppliersRow Class

Figure 34: The GetProducts() Method is Now Part of the Northwind.SuppliersRow Class

The GetProducts() method can now be used to enumerate the set of products for a particular supplier, as the following code shows:

NorthwindTableAdapters.SuppliersTableAdapter suppliersAdapter =
new NorthwindTableAdapters.SuppliersTableAdapter();
// Get all of the suppliers
Northwind.SuppliersDataTable suppliers =
suppliersAdapter.GetSuppliers();
// Enumerate the suppliers
foreach (Northwind.SuppliersRow supplier in suppliers)
{
Response.Write("Supplier: " + supplier.CompanyName);
Response.Write("<ul>");
// List the products for this supplier
Northwind.ProductsDataTable products = supplier.GetProducts();
foreach (Northwind.ProductsRow product in products)
Response.Write("<li>" + product.ProductName + "</li>");
Response.Write("</ul><p> </p>");
}

This data can also be displayed in any of ASP.NET's data Web controls. The following page uses a GridView control with two fields:

  • A BoundField that displays the name of each supplier, and
  • A TemplateField that contains a BulletedList control that is bound to the results returned by the GetProducts()method for each supplier.

We'll examine how to display such master-detail reports in future tutorials. For now, this example is designed to illustrate using the custom method added to the Northwind.SuppliersRow class.

SuppliersAndProducts.aspx

<%@ Page Language="C#" CodeFile="SuppliersAndProducts.aspx.cs"
AutoEventWireup="true" Inherits="SuppliersAndProducts" %>
<!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>Untitled Page</title>
<link href="Styles.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>
Suppliers and Their Products</h2>
<p>
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False"
CssClass="DataWebControlStyle">
<HeaderStyle CssClass="HeaderStyle" />
<AlternatingRowStyle CssClass="AlternatingRowStyle" />
<Columns>
<asp:BoundField DataField="CompanyName"
HeaderText="Supplier" />
<asp:TemplateField HeaderText="Products">
<ItemTemplate>
<asp:BulletedList ID="BulletedList1"
runat="server" DataSource="<%# ((Northwind.SuppliersRow) ((System.Data.DataRowView) Container.DataItem).Row).GetProducts() %>"
DataTextField="ProductName">
</asp:BulletedList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</p>
</div>
</form>
</body>
</html>

SuppliersAndProducts.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using NorthwindTableAdapters;
public partial class SuppliersAndProducts : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SuppliersTableAdapter suppliersAdapter = new
SuppliersTableAdapter();
GridView1.DataSource = suppliersAdapter.GetSuppliers();
GridView1.DataBind();
}
}

The Supplier's Company Name is Listed in the Left Column, Their Products in the Right

Figure 35: The Supplier's Company Name is Listed in the Left Column, Their Products in the Right