<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/atom10full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><feed xmlns="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/" xmlns:georss="http://www.georss.org/georss" xmlns:gd="http://schemas.google.com/g/2005" xmlns:thr="http://purl.org/syndication/thread/1.0" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" gd:etag="W/&quot;CE4NQn08fCp7ImA9WhRRFEk.&quot;"><id>tag:blogger.com,1999:blog-4074757583328233322</id><updated>2011-11-27T17:16:33.374-08:00</updated><title>Apsdians Blog</title><subtitle type="html" /><link rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml" href="http://apsdians.blogspot.com/feeds/posts/default" /><link rel="alternate" type="text/html" href="http://apsdians.blogspot.com/" /><author><name>Manoj Chavan</name><uri>http://www.blogger.com/profile/10656208957677029383</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="31" src="http://2.bp.blogspot.com/_pwedvTzC2Ig/SiNxe2TBDtI/AAAAAAAAAE0/vSjJtAmr3GI/S220/man.jpg" /></author><generator version="7.00" uri="http://www.blogger.com">Blogger</generator><openSearch:totalResults>11</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/atom+xml" href="http://feeds.feedburner.com/ApsdiansBlog" /><feedburner:info uri="apsdiansblog" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><entry gd:etag="W/&quot;DEMMRHw4eyp7ImA9Wx9REEk.&quot;"><id>tag:blogger.com,1999:blog-4074757583328233322.post-3912360754283465300</id><published>2010-12-10T21:46:00.000-08:00</published><updated>2010-12-10T21:48:05.233-08:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2010-12-10T21:48:05.233-08:00</app:edited><title>Linq</title><content type="html">Most programmers today are required to integrate some sort of data into their applications. Often, you have to take data from multiple sources such as memory collections, relational databases, XML files, etc. With the current implementation of .NET Framework, getting to this data is often tedious and requires familiarity with multiple data access technologies and XML APIs. To make matters worse, all data sources have different means of querying the data in them: SQL for databases, XQuery for XML, LDAP queries for Active Directory etc. In short, today's data access story lacks a unified approach to accessing data from disparate data sources, which is exactly what the LINQ (Language INtegrated Query) family of technologies are intended to solve. In this series of article, you will understand all about LINQ including the basics of LINQ to performing data access using LINQ. The first installment of this series will focus on the basics of LINQ introducing the new features of C# 3.0 and how they can be used in conjunction with LINQ.&lt;br /&gt;&lt;br /&gt;Introduction to LINQ&lt;br /&gt;&lt;br /&gt;The official goal of LINQ family of technologies is to add "general purpose query facilities to the .NET Framework that apply to all sources of information, not just relational or XML data". One of the nice things about LINQ is that it integrates seamlessly with the existing .NET languages such as C#, VB.NET because the underlying LINQ API is just nothing but a set of .NET classes that operate like any other .NET class. In addition, the query functionality is not just restricted to SQL or XML data; you can apply LINQ to query any class as long as that class implements IEnumerable&lt;T&gt; class.&lt;br /&gt;&lt;br /&gt;As mentioned before, LINQ is a family of technologies that provide querying features and class patterns that DLinq and XLinq. DLinq (also referred to as LINQ to SQL) is specifically the version of LINQ that focuses on querying data from relational data sources. XLinq (LINQ to XML) is that aspect of LINQ that is geared towards querying XML data. To run the code samples supplied with this article, you need Visual Studio 2005 Professional RTM as well as LINQ May 2006 Community Technology Preview.&lt;br /&gt;&lt;br /&gt;Simple LINQ Example&lt;br /&gt;&lt;br /&gt;To start with, create a new Visual C# LINQ Windows Application project using Visual Studio 2005. Notice that the Visual Studio automatically adds the following LINQ namespaces.&lt;br /&gt;&lt;br /&gt;using System.Query;&lt;br /&gt;using System.Data.DLinq;&lt;br /&gt;using System.Xml.XLinq;&lt;br /&gt;&lt;br /&gt;Out of the above namespaces, System.Query namespace is the core namespace that exposes standard LINQ query operators.&lt;br /&gt;&lt;br /&gt;As a start, open up the form add the logic that loops through an array of string using LINQ. To this end, add a command button to the form and modify its Click event to look like the following:&lt;br /&gt;&lt;br /&gt;private void btnLoopThroughStrings_Click(object sender, EventArgs e)&lt;br /&gt;{&lt;br /&gt;    string[] names = {"John", "Peter", "Joe", "Patrick", "Donald", "Eric"};&lt;br /&gt;    IEnumerable&lt;string&gt; namesWithFiveCharacters =&lt;br /&gt;                                from name in names&lt;br /&gt;                                where name.Length &lt; 5&lt;br /&gt;                                select name;&lt;br /&gt;    lstResults.Items.Clear();&lt;br /&gt;    foreach(var name in namesWithFiveCharacters)&lt;br /&gt;        lstResults.Items.Add(name);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;Note that the above code assumes that there is a list box named lstResults added to the form and this list box is meant to display the results of the query. If you were to compile and run this program, you would see the below output:&lt;br /&gt;&lt;br /&gt;Let us walk through the code line by line.&lt;br /&gt;&lt;br /&gt;First, you declare a string array called names.&lt;br /&gt;&lt;br /&gt;string[] names = {"John", "Peter", "Joe", "Patrick", "Donald", "Eric"};&lt;br /&gt;&lt;br /&gt;Then you loop through the names array using the LINQ syntax. As shown below, the new LINQ syntax code enables you to query from any type of data source in a way that is very similar to querying from a table in T-SQL.&lt;br /&gt;&lt;br /&gt;IEnumerable&lt;string&gt; namesWithFiveCharacters =&lt;br /&gt;                            from name in names&lt;br /&gt;                            where name.Length &lt; 5&lt;br /&gt;                            select name;&lt;br /&gt;&lt;br /&gt;The above syntax is functionally similar to the T-SQL statement in that this allows you to query the names array using the from..where..select syntax. The main difference is the use of "from name in names" syntax in the beginning and the appearance of "select name" at the end.&lt;br /&gt;&lt;br /&gt;Essentially, you retrieve data from an array of names using the "where" clause as a filtering mechanism. It is very important to note that it you need a way to refer to the objects inside the collection so that you can use standard query operators like where with those objects. In this case, "name" is used to refer to the each object inside the names array. Now that you have understood the basics of LINQ, let us extend our scope to query collections that contain objects.&lt;br /&gt;&lt;br /&gt;An In-Depth look at LINQ&lt;br /&gt;&lt;br /&gt;In this section, let us look at closer look at LINQ. To really understand LINQ, you also need to understand the new language features of C# 3.0. Specifically, it would be beneficial to discuss LINQ in the context of the below features of C# 3.0:&lt;br /&gt;&lt;br /&gt;    * Type Inference&lt;br /&gt;    * Lamda Expressions&lt;br /&gt;    * Extension Methods&lt;br /&gt;    * Anonymous Types&lt;br /&gt;&lt;br /&gt;The next few sections will discuss the above features in the context of leveraging them using LINQ. To get started with LINQ, all you need to do is to import the System.Query namespace. This namespace contains a number of classes that enable you to accomplish a lot with LINQ.&lt;br /&gt;&lt;br /&gt;Type Inference&lt;br /&gt;&lt;br /&gt;To understand type inference, let us look at couple of lines of code.&lt;br /&gt;&lt;br /&gt;var count = 1;&lt;br /&gt;var output = "This is a string";&lt;br /&gt;var employees = new EmployeesCollection();&lt;br /&gt;&lt;br /&gt;In the above lines of code, the compiler sees the var keyword, looks at the assignment to count, and determines that it should be an Int32, then assigns 1 to it. When it sees that you assign a string to the output variable, it determines that output should be of type System.String. Same goes for employees collection object. As you would have guessed by now, var is a new keyword introduced in C# 3.0 that has a special meaning. var is used to signal the compiler that you are using the new Local Variable Type Inference feature in C# 3.0.&lt;br /&gt;&lt;br /&gt;As an example, let us modify our string query example to use the var keyword.&lt;br /&gt;&lt;br /&gt;private void btnLoopThroughStrings_Click(object sender, EventArgs e)&lt;br /&gt;{&lt;br /&gt;    string[] names = {"John", "Peter", "Joe", "Patrick", "Donald", "Eric"};&lt;br /&gt;    var namesWithFiveCharacters =&lt;br /&gt;                            from name in names&lt;br /&gt;                            where name.Length &lt; 5&lt;br /&gt;                            select name'&lt;br /&gt;    lstResults.Items.Clear();&lt;br /&gt;    foreach(var name in namesWithFiveCharacters)&lt;br /&gt;        lstResults.Items.Add(name);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;As the above code shows, the variable namesWithFiveCharacters now uses the type "var" instead of IEnumerable&lt;string&gt;. Using "var" is much more extensible since it tells the compiler to infer the type from the assignment. In this case, based on the results of the query, which is IEnumerable&lt;string&gt;, the compiler will automatically assume that it is a variable of type IEnumerable&lt;string&gt;.&lt;br /&gt;&lt;br /&gt;If you run the code, it still produces the same output.&lt;br /&gt;&lt;br /&gt;Lambda Expressions&lt;br /&gt;&lt;br /&gt;C# 2.0 introduced a new feature, anonymous methods, that allows you to declare your method code inline instead of with a delegate function. Lambda expressions, a new feature in C# 3.0, have a more concise syntax to achieve the same goal. Take a closer look at anonymous methods before discussing lambda expressions. Suppose you want to create a button that displays a message box when you click it. In C# 2.0, you would do it as follows:&lt;br /&gt;&lt;br /&gt;public SimpleForm()&lt;br /&gt;{&lt;br /&gt;    addButton = new Button(...);&lt;br /&gt;    addButton.Click += delegate&lt;br /&gt;    {&lt;br /&gt;        MessageBox.Show ("Button clicked");&lt;br /&gt;    };&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;As the above code shows, you can use anonymous methods to declare the function logic inline. However C# 3.0 introduces an even simpler syntax, lambda expressions, which you write as a parameter list followed by the "=&gt;" token, followed by an expression or a statement block. Lambda Expressions are the natural evolution of C# 2.0's Anonymous Methods. Essentially, a Lambda Expression is a convenient syntax that is used to assign a chunk of code (the anonymous method) to a variable (the delegate). As an example,&lt;br /&gt;&lt;br /&gt;employee =&gt; employee.StartsWith("D");&lt;br /&gt;&lt;br /&gt;In this case, the delegates used in the above query are defined in the System.Query namespace as such:&lt;br /&gt;&lt;br /&gt;public delegate T Func&lt;T&gt;();&lt;br /&gt;public delegate T Func&lt;A0, T&gt;(A0 arg0);&lt;br /&gt;&lt;br /&gt;So this code snippet could be written as:&lt;br /&gt;&lt;br /&gt;Func&lt;string, bool&gt; person = delegate (string s) {&lt;br /&gt;                        return s.StartsWith("D"); };&lt;br /&gt;&lt;br /&gt;As you can see, the lambda expression is a lot more compact than the above one. Lambda Expressions are basically just a compact version of anonymous Methods, and you can use either of them or even regular named methods when creating filters for these query operators. Lambda Expressions, though, have the benefit of being compiled either to IL or to an Expression Tree, depending on how they are used.&lt;br /&gt;&lt;br /&gt;Note that you can also pass parameters to Lambda expressions, which can be explicitly or implicitly typed. In an explicitly typed parameter list, the type of each expression is explicitly specified. In an implicitly typed parameter list, the types are inferred from the context in which the lambda expression occurs:&lt;br /&gt;&lt;br /&gt;(int count) =&gt; count + 1    //explicitly typed parameter&lt;br /&gt;(y,z) =&gt; return y * z;      //implicitly typed parameter&lt;br /&gt;&lt;br /&gt;Extension Methods&lt;br /&gt;&lt;br /&gt;Previously you understood how the query operators such as StartsWith can be used with the dot notation. You might wonder where these methods come from. These methods, which reside in the System.Query.Sequence class, are part of a new feature in C# 3.0 called Extension Methods. Extension Method is a new way of extending existing types. Basically, this works by adding a "this" modifier on the first argument. For example, the Sequence class has the Where operator defined as follows:&lt;br /&gt;&lt;br /&gt;public static IEnumerable&lt;T&gt; Where&lt;T&gt;(&lt;br /&gt;    this IEnumerable&lt;T&gt; source, Func&lt;T, bool&gt; predicate) {&lt;br /&gt;        foreach (T element in source) {&lt;br /&gt;            if (predicate(element)) yield return element;&lt;br /&gt;        }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;Note the use of "this" modifier on the first argument. The compiler sees this and treats it as a new method on the specified type. So now IEnumerable&lt;T&gt; gets the Where() method. Here it is important to remember that the explicitly defined methods in the object get the first priority. For example, if you call Where() on an object, then the compiler goes to find Where() on the object itself first. If Where() is not present, then it goes off to find an Extension Method that matches the method signature. Clearly, while this feature is cool and really powerful, extension methods should be used extremely sparingly.&lt;br /&gt;&lt;br /&gt;Note that C# 3.0 also makes it possible to add methods to existing classes that are defined in other assemblies. All the extension methods must be declared static and they are very similar to static methods. Note that you can declare them only in static classes. To declare an extension method, you specify the keyword "this" as the first parameter of the method, for example:&lt;br /&gt;&lt;br /&gt;public static class StringExtension&lt;br /&gt;{&lt;br /&gt;    public static void Echo(this string s)&lt;br /&gt;    {&lt;br /&gt;        Console.WriteLine("Supplied string : " + s);&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;The above code shows the extension method named Echo declared in the StringExtension class. Now you can invoke the Echo method like an instance method with a string. The string is passed with the first parameter of the method.&lt;br /&gt;&lt;br /&gt;string s = "Hello world";&lt;br /&gt;s.Echo();&lt;br /&gt;&lt;br /&gt;Based on the above code, here are the key characteristics of extension methods.&lt;br /&gt;&lt;br /&gt;   1. Extension methods have the keyword this before the first argument&lt;br /&gt;   2. When extension methods are consumed, the argument that was declared with the keyword this is not passed. In the above code, note the invocation of Echo() method without any arguments&lt;br /&gt;   3. Extension methods can be defined only in a static class&lt;br /&gt;   4. Extension methods can be called only on instances. Trying to call them on a class will result in compilation errors. The class instances on which they are called are determined by the first argument in the declaration, the one having the keyword this.&lt;br /&gt;&lt;br /&gt;Using Collections in LINQ&lt;br /&gt;&lt;br /&gt;Now that you have seen the basics of LINQ and C# 3.0, let us look at a slightly more interesting example. First, let us define a new class named Person:&lt;br /&gt;&lt;br /&gt;public class Person&lt;br /&gt;{&lt;br /&gt;    private string _firstName;&lt;br /&gt;    private string _lastName;&lt;br /&gt;    private string _address;&lt;br /&gt;&lt;br /&gt;    public Person(){}&lt;br /&gt;&lt;br /&gt;    public string FirstName&lt;br /&gt;    {&lt;br /&gt;        get { return _firstName; }&lt;br /&gt;        set{_firstName = value; }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public string LastName&lt;br /&gt;    {&lt;br /&gt;        get { return _lastName; }&lt;br /&gt;        set { _lastName = value; }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public string Address&lt;br /&gt;    {&lt;br /&gt;        get{return _address; }&lt;br /&gt;        set{ _address = value; }&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;Now let us create a Person collection and query it using LINQ. You add a button to the form, name it btnLoopThroughObjects and modify its Click event to look like the following:&lt;br /&gt;&lt;br /&gt;private void btnLoopThroughObjects_Click(object sender, EventArgs e)&lt;br /&gt;{&lt;br /&gt;    List&lt;Person&gt; persons = new List&lt;Person&gt;&lt;br /&gt;        {new Person{FirstName = "Joe", LastName = "Adams", Address = "Chandler"},&lt;br /&gt;        new Person{FirstName = "Don", LastName ="Alexander", Address = "Washington"},&lt;br /&gt;        new Person{FirstName = "Dave", LastName = "Ashton", Address = "Seattle"},&lt;br /&gt;        new Person{FirstName = "Bill", LastName = "Pierce", Address = "Sacromento"},&lt;br /&gt;        new Person{FirstName = "Bill", LastName ="Giard", Address = "Camphill"}};&lt;br /&gt;    var personsNotInSeattle = from person in persons&lt;br /&gt;                              where person.Address != "Seattle"&lt;br /&gt;                              orderby person.FirstName&lt;br /&gt;                              select person;&lt;br /&gt;    lstResults.Items.Clear();&lt;br /&gt;    foreach (var person in personsNotInSeattle)&lt;br /&gt;    {&lt;br /&gt;        lstResults.Items.Add(person.FirstName + " " + person.LastName +&lt;br /&gt;            " - " + person.Address);&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;The above code shows off a few cool features. The first is the new C# 3.0 support for creating class instances, and then using a terser syntax for setting properties on them:&lt;br /&gt;&lt;br /&gt;new Person{FirstName = "Dave", LastName = "Ashton", Address = "Seattle"}&lt;br /&gt;&lt;br /&gt;This is very useful when instantiating and adding classes within a collection like above (or within an anonymous type). Note that this example uses a Generics based List collection of type "Person". LINQ supports executing queries against any IEnumerable&lt;T&gt; collection, so can be used against any Generics or non-Generics based object collections you already have.&lt;br /&gt;&lt;br /&gt;After creating the collection, you loop through the collection and filter out all the persons that are not in Seattle and order the results by first name of the persons using the below query.&lt;br /&gt;&lt;br /&gt;var personsNotInSeattle = from person in persons&lt;br /&gt;                          where person.Address != "Seattle"&lt;br /&gt;                          orderby person.FirstName&lt;br /&gt;                          select person;&lt;br /&gt;&lt;br /&gt;The concept in this example is rather simple. It examines all persons using a compound from clause. If the address of a person is not equal to Seattle, the method adds that person to the resulting collection. The output produced by the above code is as follows:&lt;br /&gt;&lt;br /&gt;Anonymous Types&lt;br /&gt;&lt;br /&gt;In the previous section, the output from the query is an array of the persons. In the query, you specify that you only want those persons that are not in Seattle. In that case, you returned an array of Person objects with each Person object containing FirstName, LastName, and Address properties.&lt;br /&gt;&lt;br /&gt;Let us say for example, you just want all the persons that meet the criteria but only with FirstName and Address properties. This means that you need to be able to create an unknown class with these two properties programmatically on the fly. This is exactly what the Anonymous Types in C# 3.0 allows you to accomplish this. Although these types are called anonymous types, CLR does assign a name to these types. But they are just unknown to us.&lt;br /&gt;&lt;br /&gt;For example, the below snippet of code represents the Click event of a command button returns a sequence of a new type when queried using LINQ.&lt;br /&gt;&lt;br /&gt;private void btnLoopThroughAnonymous_Click(object sender, EventArgs e)&lt;br /&gt;{&lt;br /&gt;    List&lt;Person&gt; persons = new List&lt;Person&gt;&lt;br /&gt;        {new Person{FirstName = "Joe", LastName = "Adams", Address = "Chandler"},&lt;br /&gt;        new Person{FirstName = "Don", LastName ="Alexander", Address = "Washington"},&lt;br /&gt;        new Person{FirstName = "Dave", LastName = "Ashton", Address = "Seattle"},&lt;br /&gt;        new Person{FirstName = "Bill", LastName = "Pierce", Address = "Sacromento"},&lt;br /&gt;        new Person{FirstName = "Bill", LastName ="Giard", Address = "Camphill"}};&lt;br /&gt;    var personsNotInSeattle = from person in persons&lt;br /&gt;                              where person.Address != "Seattle"&lt;br /&gt;                              orderby person.FirstName&lt;br /&gt;                              select new {person.FirstName,&lt;br /&gt;                              person.Address};&lt;br /&gt;    lstResults.Items.Clear();&lt;br /&gt;    foreach (var person in personsNotInSeattle)&lt;br /&gt;    {&lt;br /&gt;        lstResults.Items.Add(person.FirstName + " --- " + person.Address );&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;Before discussing the code in detail, here is the output produced by the above code.&lt;br /&gt;&lt;br /&gt;The above snippet of code is very similar to previous example in that here also you examine all persons using a compound from clause and return only those persons that are not in Seattle. However one key difference is that it does not return the entire person. It returns a new type that contains two public properties: FirstName, Address. This new type was created by the compiler. Here is the definition the compiler creates:&lt;br /&gt;&lt;br /&gt;public class ?????&lt;br /&gt;{&lt;br /&gt;    private string firstName;&lt;br /&gt;    private string address;&lt;br /&gt;&lt;br /&gt;    public string FirstName&lt;br /&gt;    {&lt;br /&gt;        get { return firstName; }&lt;br /&gt;        set { firstName= value; }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public string Address&lt;br /&gt;    {&lt;br /&gt;        get { return address; }&lt;br /&gt;        set { address = value; }&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;As you can see the above class is very similar to the Person class except that it is nameless meaning that it is an anonymous type. So the return value from the query is IEnumerable&lt;?????&gt; and what goes as a replacement for the question mark is something that is determined by the compiler. To be able to capture this collection of anonymous return type, you need a variable that can hold any object types including the compiler created types. This is exactly why you need a var keyword. As mentioned before, the var keyword is used to declare local variables when you do not know the name of the anonymous type that the compiler created for you. Variables declared with var must be initialized at the point they are declared, because it is the only way the compiler knows what type they might be.&lt;br /&gt;&lt;br /&gt;DLinq and XLinq&lt;br /&gt;&lt;br /&gt;Of course, data does not just exist in .NET memory. Two other important places where you will find data are databases and XML documents. This is where DLinq (LINQ to SQL) and XLinq (LINQ to XML) shine. DLinq provides special objects in addition to the standard LINQ objects that allow querying straight from the database. DLinq allows for data mapping through a simple class based mechanism. All query expressions are then dealt with as an "expression tree", which allows any LINQ expression to be converted into a different equivalent expression such as T-SQL. Using this technique, the following C# code snippet can actually perform a native query in SQL Server:&lt;br /&gt;&lt;br /&gt;from c in customers&lt;br /&gt;    where c.LastName.StartsWith("A")&lt;br /&gt;    select c&lt;br /&gt;&lt;br /&gt;By way of an expression tree, this C# query gets translated into a valid T-SQL query which then executes on the server. C# developers never need to learn the native T-SQL syntax. Also, think of the possibilities this opens up for CLR stored procedures!&lt;br /&gt;&lt;br /&gt;As mentioned before XLinq enables you to query XML data. Using XLinq, you can query all customers whose last name starts with an "A" in the following fashion:&lt;br /&gt;&lt;br /&gt;from c in customerXml.Descendants("Customer")&lt;br /&gt;    where c.Element("LastName").Value.StartsWith("A")&lt;br /&gt;    select c&lt;br /&gt;&lt;br /&gt;XLinq is more powerful than DLinq, because in addition to querying XML, it can also create XML. Note that this article has just given you a flavor of DLinq and XLinq and the next couple of installments of this article series will go into more details on DLinq and XLinq.&lt;br /&gt;&lt;br /&gt;Conclusion&lt;br /&gt;&lt;br /&gt;In this part, we looked at the current state of today's data access story. Then we looked at how LINQ and the new language features in C# 3.0 solve these issues by providing us with a consistent set of Standard Query Operators that we can use to query any collection that implements IEnumerable&lt;T&gt;. In this installment, we only focused on in-memory collections of data in order to avoid the confusion that most people have when mixing LINQ with DLinq and XLinq, but rest assured these will be covered in the future installments of this article. Furthermore, because LINQ is just a set of methods that adhere to the naming conventions for the Standard Query Operators, anybody can implement their own LINQ based collections for accessing any other type of data.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4074757583328233322-3912360754283465300?l=apsdians.blogspot.com' alt='' /&gt;&lt;/div&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/C6_US8puWLv124qnazUYybQUAss/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/C6_US8puWLv124qnazUYybQUAss/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/C6_US8puWLv124qnazUYybQUAss/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/C6_US8puWLv124qnazUYybQUAss/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/ApsdiansBlog/~4/9w_xtYk658s" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://apsdians.blogspot.com/feeds/3912360754283465300/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://apsdians.blogspot.com/2010/12/linq.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/4074757583328233322/posts/default/3912360754283465300?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/4074757583328233322/posts/default/3912360754283465300?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/ApsdiansBlog/~3/9w_xtYk658s/linq.html" title="Linq" /><author><name>Manoj Chavan</name><uri>http://www.blogger.com/profile/10656208957677029383</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="31" src="http://2.bp.blogspot.com/_pwedvTzC2Ig/SiNxe2TBDtI/AAAAAAAAAE0/vSjJtAmr3GI/S220/man.jpg" /></author><thr:total>0</thr:total><feedburner:origLink>http://apsdians.blogspot.com/2010/12/linq.html</feedburner:origLink></entry><entry gd:etag="W/&quot;DEQNQH86fyp7ImA9WxJUEkQ.&quot;"><id>tag:blogger.com,1999:blog-4074757583328233322.post-5121465909631225025</id><published>2009-07-02T06:09:00.000-07:00</published><updated>2009-07-11T00:13:11.117-07:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2009-07-11T00:13:11.117-07:00</app:edited><title>AJAX</title><content type="html">hi&lt;span style="font-size:85%;"&gt;....&lt;/span&gt;&lt;br /&gt;&lt;br&gt;&lt;br /&gt;VISIT THIS SITE HAVING FUN WITH VIDEOS ON AJAX :-&lt;br&gt;&lt;br /&gt;&lt;a href="www.asp.net/LEARN/ajax-videos/"&gt;AJAX with www.asp.net/LEARN/ajax-videos/&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4074757583328233322-5121465909631225025?l=apsdians.blogspot.com' alt='' /&gt;&lt;/div&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/g6xJMnE36k67ojMinS4RroyxmOk/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/g6xJMnE36k67ojMinS4RroyxmOk/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/g6xJMnE36k67ojMinS4RroyxmOk/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/g6xJMnE36k67ojMinS4RroyxmOk/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/ApsdiansBlog/~4/7wDXPr8SuRM" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://apsdians.blogspot.com/feeds/5121465909631225025/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://apsdians.blogspot.com/2009/07/apsdians-blog.html#comment-form" title="1 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/4074757583328233322/posts/default/5121465909631225025?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/4074757583328233322/posts/default/5121465909631225025?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/ApsdiansBlog/~3/7wDXPr8SuRM/apsdians-blog.html" title="AJAX" /><author><name>geethanair</name><uri>http://www.blogger.com/profile/18259049871514154550</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="16" height="16" src="http://img2.blogblog.com/img/b16-rounded.gif" /></author><thr:total>1</thr:total><feedburner:origLink>http://apsdians.blogspot.com/2009/07/apsdians-blog.html</feedburner:origLink></entry><entry gd:etag="W/&quot;CUAGQ309eip7ImA9WxJWFEw.&quot;"><id>tag:blogger.com,1999:blog-4074757583328233322.post-3154141073045490945</id><published>2009-05-25T21:49:00.000-07:00</published><updated>2009-06-19T05:15:22.362-07:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2009-06-19T05:15:22.362-07:00</app:edited><title>Navigation From One Page to Another Page with Data.</title><content type="html">&lt;table border="0" cellspacing="0" cellpadding="0" width="100%" valign="top"&gt;&lt;br /&gt;&lt;tbody&gt;&lt;br /&gt;&lt;tr&gt;&lt;br /&gt;&lt;td bgcolor="#e1e1e1" align="middle"&gt;&lt;br /&gt;&lt;b&gt;Navigation From One Page to Another Page with Data. &lt;/b&gt;&lt;br /&gt;&lt;br /&gt;&lt;/td&gt;&lt;br /&gt;&lt;/tr&gt;&lt;br /&gt;&lt;tr&gt;&lt;br /&gt;&lt;td&gt;&lt;br /&gt;There are various ways to send the data from one page to other&lt;br /&gt;&lt;/td&gt;&lt;br /&gt;&lt;/tr&gt;&lt;br /&gt;&lt;tr&gt;&lt;td&gt;&lt;br /&gt;1&gt;&lt;u&gt;&lt;b&gt; Using QueryString.&lt;/b&gt;&lt;/u&gt;&lt;br /&gt;&lt;/td&gt;&lt;/td&gt;&lt;br /&gt;&lt;tr&gt;&lt;td&gt;&lt;br /&gt;e.g.&lt;br /&gt;In first page you can write as follows :&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Response.Redirect("mypage.aspx?id=" + value from control or variable or anystring);&lt;br /&gt;mypage.aspx?id=10&lt;/b&gt;&lt;br /&gt;&lt;br /&gt;Above dummy my page now contains id as the query string&lt;br /&gt;and&lt;br /&gt;It can be retrieved on the other page as follows :&lt;br /&gt;&lt;br /&gt;&lt;b&gt;string id = Request.QueryString["id"].ToString();&lt;/b&gt;&lt;br /&gt;&lt;/td&gt;&lt;/td&gt;&lt;br /&gt;&lt;tr&gt;&lt;td&gt;&lt;br /&gt;2&gt; &lt;u&gt;&lt;b&gt;Using Session.&lt;/b&gt;&lt;/u&gt;&lt;br /&gt;e.g. You can create session in first page like.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Session["id"] = value from control or variable or anystring;&lt;/b&gt;&lt;br /&gt;and you can retrive it from other page as following:&lt;br /&gt;&lt;br /&gt;&lt;b&gt;string id = Session["id"].ToString();&lt;/b&gt;&lt;br /&gt;&lt;/td&gt;&lt;/td&gt;&lt;br /&gt;&lt;tr&gt;&lt;td&gt;&lt;br /&gt;3&gt;&lt;u&gt;&lt;b&gt;Using Cookies&lt;/b&gt;&lt;/u&gt;&lt;br /&gt;e.g. You can write cookie as in first page as follows :&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Response.Cookies["id"].Value = value from control or variable or anystring;&lt;b&gt;&lt;br /&gt;and to retrive cookie you can request it as follows:&lt;br /&gt;&lt;br /&gt;&lt;b&gt;string id = Request.Cookies["BackgroundColor"].Value.ToString();&lt;/b&gt;&lt;br /&gt;&lt;br /&gt;&lt;/b&gt;&lt;/b&gt;&lt;/td&gt;&lt;/td&gt;&lt;br /&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4074757583328233322-3154141073045490945?l=apsdians.blogspot.com' alt='' /&gt;&lt;/div&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/Cqn8XOcJhhhzjEhe8lZv1YVsxuI/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/Cqn8XOcJhhhzjEhe8lZv1YVsxuI/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/Cqn8XOcJhhhzjEhe8lZv1YVsxuI/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/Cqn8XOcJhhhzjEhe8lZv1YVsxuI/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/ApsdiansBlog/~4/Xnk1tPd_ayM" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://apsdians.blogspot.com/feeds/3154141073045490945/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://apsdians.blogspot.com/2009/05/navigation-from-one-page-to-another.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/4074757583328233322/posts/default/3154141073045490945?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/4074757583328233322/posts/default/3154141073045490945?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/ApsdiansBlog/~3/Xnk1tPd_ayM/navigation-from-one-page-to-another.html" title="Navigation From One Page to Another Page with Data." /><author><name>Manoj Chavan</name><uri>http://www.blogger.com/profile/10656208957677029383</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="31" src="http://2.bp.blogspot.com/_pwedvTzC2Ig/SiNxe2TBDtI/AAAAAAAAAE0/vSjJtAmr3GI/S220/man.jpg" /></author><thr:total>0</thr:total><feedburner:origLink>http://apsdians.blogspot.com/2009/05/navigation-from-one-page-to-another.html</feedburner:origLink></entry><entry gd:etag="W/&quot;A0ICQnw9eCp7ImA9WxJQGUw.&quot;"><id>tag:blogger.com,1999:blog-4074757583328233322.post-2562728756544981446</id><published>2009-05-22T22:15:00.000-07:00</published><updated>2009-06-01T22:12:43.260-07:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2009-06-01T22:12:43.260-07:00</app:edited><title>Advanced Diploma in Software Development</title><content type="html">&lt;table width="100%"&gt;&lt;br /&gt;&lt;tbody&gt;&lt;tr&gt;&lt;br /&gt;&lt;td&gt;&lt;br /&gt;&lt;b&gt;&lt;span style="color:red;"&gt;Advanced Diploma in Software Development (ADSD) &lt;/span&gt;&lt;/b&gt;&lt;br /&gt;&lt;br /&gt;&lt;b&gt;About ADSD&lt;/b&gt;&lt;br /&gt;&lt;p&gt;&lt;br /&gt;Advanced Diploma in Software Development (ADSD) is an autonomous programme that has been specially designed based on IT industry requirements, professional feedback and dynamic research. To achieve the objectives of quality, practical and focused IT education, MET ISDR's ADSD programme ensures excellent IT career opportunities by turning all graduates into industry ready software developers.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;ADSD does not require any previous knowledge of programming. Especially for the non-engineering and the non-IT graduates who don't have any programming language in their formal curriculum. This programme requires candidates with good aptitude, analytical and logical skills, so that they can grasp the concepts of programming smoothly.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Right from the Programming Languages &amp;amp; Operating Systems, ADSD will deliver the Enterprise Application Development using the latest platforms so that the students are equipped with all the tools and technologies which will help them in creating their own successful position in the community of knowledge professionals.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;&lt;br /&gt;&lt;b&gt;&lt;br /&gt;Programme Objective&lt;br /&gt;&lt;/b&gt;&lt;br /&gt;&lt;br /&gt;This is a programme specially designed for all the graduates who want to make their career in the IT industry.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Are you eligible?&lt;/b&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Successful completion of 10 + 2 + 3 or 4 or equivalent from a recognised University with minimum 50% at degree level.&lt;br /&gt;Computer Science or IT Diploma holders from the recognised technical boards with 2 years of relevant IT experience can apply.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;b&gt;How can I apply?&lt;/b&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;1. Obtain Application Form and Prospectus, available at MET for Rs. 600/- in cash or DD payable at Mumbai in favour of&lt;br /&gt;&lt;b&gt;'MET ISDR'.&lt;/b&gt; You can also pay online (click here) and the same will be sent to you.&lt;br /&gt;2. Fill the Application Form and submit the same with necessary documents (mentioned in the Prospectus).&lt;br /&gt;3. Appear for the Selection Procedure on scheduled date.&lt;br /&gt;&lt;b&gt;&lt;br /&gt;Important Dates&lt;/b&gt;&lt;br /&gt;&lt;/p&gt;&lt;table&gt;&lt;br /&gt;&lt;tbody&gt;&lt;tr&gt;&lt;br /&gt;&lt;td&gt;&lt;br /&gt;1.&lt;br /&gt;&lt;/td&gt;&lt;br /&gt;&lt;td&gt;&lt;br /&gt;Last Date of Form Submission (Registration Closes) June 29, 2009&lt;br /&gt;&lt;/td&gt;&lt;br /&gt;&lt;/tr&gt;&lt;br /&gt;&lt;tr&gt;&lt;td&gt;2.&lt;/td&gt;&lt;br /&gt;&lt;td&gt;Entrance Exam and Selection Procedure July 05, 2009&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;br /&gt;&lt;p&gt;&lt;/p&gt;&lt;br /&gt;Selection Procedure&lt;br /&gt;Based on the performance in the MET CET (consisting of Written Test &amp;amp; Personal Interview).&lt;br /&gt;Programme Modules&lt;br /&gt;The ADSD programme is divided into two parts. Each part consists of four modules. Each module is divided into two units.&lt;br /&gt;Following is the detailed structure:&lt;br /&gt;&lt;table border="1" width="100%"&gt;&lt;br /&gt;&lt;tbody&gt;&lt;tr&gt;&lt;br /&gt;&lt;td&gt;&lt;br /&gt;&lt;b&gt;Part I - Systems Programming&lt;/b&gt;&lt;br /&gt;&lt;/td&gt;&lt;br /&gt;&lt;td&gt;&lt;br /&gt;&lt;b&gt;Part II - Application Programming&lt;br /&gt;&lt;/b&gt;&lt;br /&gt;&lt;/td&gt;&lt;br /&gt;&lt;/tr&gt;&lt;br /&gt;&lt;tr&gt;&lt;br /&gt;&lt;td&gt;&lt;br /&gt;&lt;b&gt;Module 1&lt;/b&gt;: Programming Foundations&lt;br /&gt;&lt;br /&gt;Unit 1: Assembly and C Programming&lt;br /&gt;&lt;br /&gt;Unit 2: C++ Programming&lt;br /&gt;&lt;/td&gt;&lt;br /&gt;&lt;td&gt;&lt;br /&gt;&lt;b&gt;Module 5&lt;/b&gt;: Web Programming&lt;br /&gt;&lt;br /&gt;Unit 1: The Client Side&lt;br /&gt;&lt;br /&gt;Unit 2: The Server Side&lt;br /&gt;&lt;br /&gt;&lt;/td&gt;&lt;br /&gt;&lt;/tr&gt;&lt;br /&gt;&lt;tr&gt;&lt;br /&gt;&lt;td&gt;&lt;br /&gt;&lt;b&gt;Module 2&lt;/b&gt;: Linux System Programming&lt;br /&gt;&lt;br /&gt;Unit 1: The Kernel&lt;br /&gt;&lt;br /&gt;Unit 2: The Shell&lt;br /&gt;&lt;br /&gt;&lt;/td&gt;&lt;br /&gt;&lt;td&gt;&lt;br /&gt;&lt;b&gt;Module 6&lt;/b&gt;: Java Programming&lt;br /&gt;&lt;br /&gt;Unit 1: Desktop Java&lt;br /&gt;&lt;br /&gt;Unit 2: Distributed Java&lt;br /&gt;&lt;br /&gt;&lt;/td&gt;&lt;br /&gt;&lt;/tr&gt;&lt;br /&gt;&lt;br /&gt;&lt;tr&gt;&lt;br /&gt;&lt;td&gt;&lt;br /&gt;&lt;b&gt;Module 3:&lt;/b&gt; Windows System Programming&lt;br /&gt;&lt;br /&gt;Unit 1: WIN32 Platform SDK&lt;br /&gt;&lt;br /&gt;Unit 2: MFC and COM&lt;br /&gt;&lt;br /&gt;&lt;/td&gt;&lt;br /&gt;&lt;td&gt;&lt;br /&gt;&lt;b&gt;Module 7&lt;/b&gt;: .NET Programming&lt;br /&gt;&lt;br /&gt;Unit 1: Desktop .NET&lt;br /&gt;&lt;br /&gt;Unit 2: Distributed .NET&lt;br /&gt;&lt;br /&gt;&lt;/td&gt;&lt;br /&gt;&lt;/tr&gt;&lt;br /&gt;&lt;br /&gt;&lt;tr&gt;&lt;br /&gt;&lt;td&gt;&lt;br /&gt;&lt;b&gt;Module 4&lt;/b&gt;: SE &amp;amp; Project Management&lt;br /&gt;Unit 1: Software Engineering&lt;br /&gt;Unit 2: Project Management&lt;br /&gt;&lt;br /&gt;&lt;/td&gt;&lt;br /&gt;&lt;td&gt;&lt;br /&gt;&lt;b&gt;Module 8&lt;/b&gt;: Aptitude Skills, Communications &amp;amp; Personality Development&lt;br /&gt;Unit 1: Aptitude Skills&lt;br /&gt;Unit 2: Communications &amp;amp; Personality Development&lt;br /&gt;&lt;br /&gt;&lt;/td&gt;&lt;br /&gt;&lt;/tr&gt;&lt;br /&gt;&lt;br /&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;br /&gt;&lt;p&gt;&lt;br /&gt;Each unit spread over 3 weeks, comprises of&lt;br /&gt;&lt;br /&gt;1. Theory - 48 hours with maximum of 3 hours daily&lt;br /&gt;2. Practical - 72 hours with minimum of 4 hours daily&lt;br /&gt;Total = 36 weeks (9 months approximately)&lt;br /&gt;* Module 4 &amp;amp; Module 8 will require 15 days each (Total 1 Month)&lt;br /&gt;Total Duration: 10 Months + Project&lt;br /&gt;Programme Fee&lt;br /&gt;The fees for the entire programme is Rs. 1,08,000.&lt;br /&gt;Unique Features&lt;br /&gt;• Unique programme in line with the current requirement of the IT industry&lt;br /&gt;• State-of-the-art computer laboratory&lt;br /&gt;• Interaction with industry professionals on technical &amp;amp; non-technical topics&lt;br /&gt;• Practical hands-on sessions, extended lab sessions&lt;br /&gt;• Industry visits to IT companies&lt;br /&gt;• Educational loan assistance&lt;br /&gt;• Excellent placement assistance&lt;br /&gt;• Free-ships to meritorious and needy students&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Opportunites&lt;/b&gt;&lt;br /&gt;The Information Technology industry is the fastest growing sector significantly contributing to the Indian economy. The need of trained manpower, professional IT workforce is growing multifold. It is projected that the IT industry will need at least 6,00,000 trained software professionals by this year. And this number is likely to increase in the near future.&lt;br /&gt;ADSD's intensive programme structure is in-line with Industry needs and therefore, assures quality trained IT professionals ready to serve the industry.&lt;br /&gt;Candidates get wide range of opportunities in various sectors of IT Industry. They can make an entry as a Programmer, Software Engineer, Database Programmer, Web Programmer, System Analyst, Business Analyst, Software Tester or join in other departments like Maintenance, Support etc.&lt;br /&gt;Having acquired sound knowledge and skill sets, ADSD graduates can easily accept IT industry challenges, allowing them to succeed in short span of time.&lt;br /&gt;&lt;br /&gt;MET has a strong alumni base of over 4000 successful IT professionals worldwide with many of them at top positions in leading companies.&lt;br /&gt;Programme Outline&lt;br /&gt;The unique feature of the APSD programme is that it does not expect any previous knowledge of programming. This way it gives opportunity to all those graduates who have never learnt programming but want to make their career as an IT professional. With their domain knowledge, these professionals will doubtlessly play a key role in meeting the ever-growing demand for quality human resources.&lt;br /&gt;Right from the programming languages &amp;amp; operating systems, this programme will deliver the Enterprise Application Development using the latest platforms so that the students are equipped with all the tools and technologies which will help them in creating their own successful position in the community of knowledge professionals.&lt;br /&gt;Visit Following Site For More Information :&lt;br /&gt;&lt;a href="http://www.met.edu/Institutes/isdr/index_isdr.asp"&gt;MET ISDR&lt;/a&gt;&lt;br /&gt;&lt;/p&gt;&lt;br /&gt;&lt;/td&gt;&lt;br /&gt;&lt;/tr&gt;&lt;br /&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4074757583328233322-2562728756544981446?l=apsdians.blogspot.com' alt='' /&gt;&lt;/div&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/4jqEF4lv9nK_5s3eyy5SIm_Jzts/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/4jqEF4lv9nK_5s3eyy5SIm_Jzts/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/4jqEF4lv9nK_5s3eyy5SIm_Jzts/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/4jqEF4lv9nK_5s3eyy5SIm_Jzts/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/ApsdiansBlog/~4/6Jj0FEtcQOA" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://apsdians.blogspot.com/feeds/2562728756544981446/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://apsdians.blogspot.com/2009/05/advanced-diploma-in-software.html#comment-form" title="3 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/4074757583328233322/posts/default/2562728756544981446?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/4074757583328233322/posts/default/2562728756544981446?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/ApsdiansBlog/~3/6Jj0FEtcQOA/advanced-diploma-in-software.html" title="Advanced Diploma in Software Development" /><author><name>Manoj Chavan</name><uri>http://www.blogger.com/profile/10656208957677029383</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="31" src="http://2.bp.blogspot.com/_pwedvTzC2Ig/SiNxe2TBDtI/AAAAAAAAAE0/vSjJtAmr3GI/S220/man.jpg" /></author><thr:total>3</thr:total><feedburner:origLink>http://apsdians.blogspot.com/2009/05/advanced-diploma-in-software.html</feedburner:origLink></entry><entry gd:etag="W/&quot;CEINQn0yeSp7ImA9WxJSFko.&quot;"><id>tag:blogger.com,1999:blog-4074757583328233322.post-5779931104811815800</id><published>2009-05-03T22:27:00.000-07:00</published><updated>2009-05-06T22:03:13.391-07:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2009-05-06T22:03:13.391-07:00</app:edited><title>In-Depth look at the GridView Control</title><content type="html">&lt;div&gt;Introduction:&lt;br /&gt; In this article we will examine more features of the Grid View control. In this article we will see some of the common operations that can be performed using the GridView control. Apart from these operations there are many more functions that can be performed on the control and which we will see in the later articles.&lt;br /&gt;&lt;br /&gt;Adding a SqlDataSource and binding to GridView Control:&lt;br /&gt;In this article I will be using the Northwind database which comes with SQL Server 2000. In the last article I explained how easy it is to bind the Grid View control to the SqlDataSource. You can perform all these actions using the wizard. If you want to code and bind the datasource you can easily perform it using the following code sample:&lt;br /&gt;&lt;br /&gt;&lt;span style="color:#009900;"&gt;void Page_Load(object sender, EventArgs e)&lt;br /&gt;{&lt;br /&gt;&lt;br /&gt;if (!Page.IsPostBack)&lt;br /&gt;{&lt;br /&gt;&lt;br /&gt;// Binds the data&lt;br /&gt;&lt;br /&gt;BindData();&lt;br /&gt;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;public void BindData()&lt;br /&gt;{&lt;br /&gt;&lt;br /&gt;// you can use this line&lt;br /&gt;&lt;br /&gt;string connectionString = myDataSource.ConnectionString;&lt;br /&gt;&lt;br /&gt;// you can also use this line since by using the SqlDataSource it makes an entry in the&lt;br /&gt;// web.config file if that is what choose to do&lt;br /&gt;//string connectionString = (string)ConfigurationSettings.AppSettings["ConnectionString"];&lt;br /&gt;// if you are using Enterprise Library you can also use&lt;br /&gt;//string connectionString = (string)ConfigurationSettings.ConnectionStrings["ConnectionString"];&lt;br /&gt;&lt;br /&gt;SqlConnection myConnection = new SqlConnection(connectionString);&lt;br /&gt;&lt;br /&gt;SqlDataAdapter ad = new SqlDataAdapter("SELECT * FROM Categories", myConnection);&lt;br /&gt;&lt;br /&gt;DataSet ds = new DataSet();&lt;br /&gt;&lt;br /&gt;ad.Fill(ds, "Categories");&lt;br /&gt;&lt;br /&gt;myGridView.DataSource = ds;&lt;br /&gt;&lt;br /&gt;myGridView.DataBind();&lt;br /&gt;&lt;br /&gt;}&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;You will need to set the Bound column in order to see the text in the cells of the grid view control. This can be easily done by using the Smart tag which appears when you right click on the grid view control.&lt;br /&gt;&lt;br /&gt;&lt;a href="http://2.bp.blogspot.com/_pwedvTzC2Ig/Sf5-H-CKLqI/AAAAAAAAABg/hpXj3b9pH4Y/s1600-h/Gridview_depth_Image1.jpg"&gt;&lt;img style="TEXT-ALIGN: center; MARGIN: 0px auto 10px; WIDTH: 320px; DISPLAY: block; HEIGHT: 260px; CURSOR: hand" id="BLOGGER_PHOTO_ID_5331837684229484194" border="0" alt="" src="http://2.bp.blogspot.com/_pwedvTzC2Ig/Sf5-H-CKLqI/AAAAAAAAABg/hpXj3b9pH4Y/s320/Gridview_depth_Image1.jpg" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;I have also added a Status column to show you the checkbox column feature. The Status column is a simple bit field whose value can be either 1 or 0. If you are using Access database you can choose Yes/No Column. Once you have set up all your columns and execute the page it will display something like this:&lt;br /&gt;&lt;br /&gt;&lt;a href="http://3.bp.blogspot.com/_pwedvTzC2Ig/Sf5_VYiJHXI/AAAAAAAAABo/_LcuvZry5BI/s1600-h/Gridview_depth_Image2.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 320px; height: 106px;" src="http://3.bp.blogspot.com/_pwedvTzC2Ig/Sf5_VYiJHXI/AAAAAAAAABo/_LcuvZry5BI/s320/Gridview_depth_Image2.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5331839014192881010" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;At this moment if you try to select the Checkbox column, meaning if you try to check or uncheck the Status column it won't work. Let's see how we can make it work with our grid view control.&lt;br /&gt;&lt;br /&gt;In the above image you see that the Checkboxes are not marked. The reason is because in the database the Checkbox column is NULL. If you make the column value to either 1 or 0 you will see check marks where the value is 1. See the image below and you will have a better idea of what I mean.&lt;br /&gt;&lt;br /&gt;&lt;a href="http://2.bp.blogspot.com/_pwedvTzC2Ig/Sf5_h8nSGJI/AAAAAAAAABw/7b_hgjYKKq4/s1600-h/Gridview_depth_Image3.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 320px; height: 103px;" src="http://2.bp.blogspot.com/_pwedvTzC2Ig/Sf5_h8nSGJI/AAAAAAAAABw/7b_hgjYKKq4/s320/Gridview_depth_Image3.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5331839230036547730" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;Editing in the Grid View Control&lt;br /&gt;You can easily add the editing, updating, selecting, paging and sorting capabilities to your grid view control. Just add a new command column and you will be asked to add whatever functionality you desire.&lt;br /&gt;&lt;br /&gt;If you are using the SqlDataSource to bind to the GridView control you will get most of the features by just using the SqlDataSource wizard. Since we are binding the control at runtime we need to add most of the functionality manually.&lt;br /&gt;&lt;br /&gt;Edit Mode:&lt;br /&gt;The fields that are marked readonly = false will change into TextBoxes when the Row_Editing event triggers. Like DataGrid control its easy to set the fields in the edit mode.&lt;br /&gt;&lt;br /&gt;// Editing mode&lt;br /&gt;&lt;br /&gt;void myGridView_RowEditing(object sender, GridViewEditEventArgs e)&lt;br /&gt;{&lt;br /&gt;&lt;br /&gt;myGridView.EditIndex = e.NewEditIndex;&lt;br /&gt;&lt;br /&gt;BindData();&lt;br /&gt;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;Cancel Edit:&lt;br /&gt;If you don't like to edit the row you can press cancel link button which will fire the RowCancelingEdit event. The code to turn the row back to its original form is quite simple and straight forward.&lt;br /&gt;&lt;br /&gt;// Cancel Edit Mode&lt;br /&gt;&lt;br /&gt;void myGridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)&lt;br /&gt;{&lt;br /&gt;&lt;br /&gt;myGridView.EditIndex = -1;&lt;br /&gt;&lt;br /&gt;BindData();&lt;br /&gt;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;Selecting Row:&lt;br /&gt;Selecting row event is fired when you make a click on the select link. If you need any particular item in that row you can easily select it using the cells property:&lt;br /&gt;&lt;br /&gt;// Selecting row&lt;br /&gt;&lt;br /&gt;void myGridView_SelectedIndexChanged(object sender, EventArgs e)&lt;br /&gt;{&lt;br /&gt;&lt;br /&gt;// This will contain the selectedValue of the row&lt;br /&gt;&lt;br /&gt;string selectedCategory = myGridView.SelectedRow.Cells[1].Text;&lt;br /&gt;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;The Cells start with index '0' which means Cell[0] is CategoryID , Cell[1] is CategoryName and so on.&lt;br /&gt;&lt;br /&gt;Update Row:&lt;br /&gt;For Updating the row we first need to get the value from the row that is entered by the user into the TextBox. For this purpose you can change the bound column into a Template column which will make is easier to locate the item.&lt;br /&gt;&lt;br /&gt;After changing the CategoryName column to a tem plated column we can easily use the RowUpdating event to find the Text entered by the user.&lt;br /&gt;&lt;br /&gt;void myGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)&lt;br /&gt;{&lt;br /&gt;&lt;br /&gt;GridViewRow row = myGridView.Rows[e.RowIndex];&lt;br /&gt;&lt;br /&gt;if (row != null)&lt;br /&gt;&lt;br /&gt;{&lt;br /&gt;&lt;br /&gt;TextBox t = row.FindControl("TextBox1") as TextBox;&lt;br /&gt;&lt;br /&gt;if (t != null)&lt;br /&gt;&lt;br /&gt;{&lt;br /&gt;&lt;br /&gt;Response.Write("The Text Entered is" + t.Text);&lt;br /&gt;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;Paging:&lt;br /&gt;Paging can also be easily enabled in the grid view control. Its just like DataGrid from Asp.net 1.1. First you need to make set the allow paging property to true. And you can also set the page size. Here is a small code sample that will enable paging.&lt;br /&gt;&lt;br /&gt;// Grid View Paging&lt;br /&gt;&lt;br /&gt;void myGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)&lt;br /&gt;{&lt;br /&gt;&lt;br /&gt;myGridView.PageIndex = e.NewPageIndex;&lt;br /&gt;&lt;br /&gt;BindData();&lt;br /&gt;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;Here is a small image shown below of paging. I have limited the page size to 3 so that the distribution of page will take place. In the image below we are in the page number 2.&lt;br /&gt;&lt;br /&gt;&lt;a href="http://4.bp.blogspot.com/_pwedvTzC2Ig/Sf5_nwCYRMI/AAAAAAAAAB4/ucmo9uFJSC4/s1600-h/Gridview_depth_Image4.jpg"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 320px; height: 88px;" src="http://4.bp.blogspot.com/_pwedvTzC2Ig/Sf5_nwCYRMI/AAAAAAAAAB4/ucmo9uFJSC4/s320/Gridview_depth_Image4.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5331839329739752642" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;Using SqlDataSource to execute commands:&lt;br /&gt;You can also use the powerful SqlDataSource control to run and make your query. The SqlDataSource also contains the QUERY builder interface which can enhance the user experience in making SQL Queries. Apart from the SELECT query there are also INSERT, DELETE and UPDATE query builders wizards that you can use in your application.&lt;br /&gt;&lt;br /&gt;When you use SqlDataSource you gets the advantage of having the paging, sorting implemented automatically which is pretty cool in some cases.&lt;br /&gt;&lt;br /&gt;In the next article we will see some more features of the Grid View control. I hope you liked the article&lt;br /&gt;&lt;br /&gt;Happy Programming ! &lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4074757583328233322-5779931104811815800?l=apsdians.blogspot.com' alt='' /&gt;&lt;/div&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/AganbbV8GPnLQa_DJop2wvi97qc/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/AganbbV8GPnLQa_DJop2wvi97qc/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/AganbbV8GPnLQa_DJop2wvi97qc/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/AganbbV8GPnLQa_DJop2wvi97qc/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/ApsdiansBlog/~4/3w7DQ0_MIBU" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://apsdians.blogspot.com/feeds/5779931104811815800/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://apsdians.blogspot.com/2009/05/in-depth-look-at-gridview-control.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/4074757583328233322/posts/default/5779931104811815800?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/4074757583328233322/posts/default/5779931104811815800?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/ApsdiansBlog/~3/3w7DQ0_MIBU/in-depth-look-at-gridview-control.html" title="In-Depth look at the GridView Control" /><author><name>Manoj Chavan</name><uri>http://www.blogger.com/profile/10656208957677029383</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="31" src="http://2.bp.blogspot.com/_pwedvTzC2Ig/SiNxe2TBDtI/AAAAAAAAAE0/vSjJtAmr3GI/S220/man.jpg" /></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://2.bp.blogspot.com/_pwedvTzC2Ig/Sf5-H-CKLqI/AAAAAAAAABg/hpXj3b9pH4Y/s72-c/Gridview_depth_Image1.jpg" height="72" width="72" /><thr:total>0</thr:total><feedburner:origLink>http://apsdians.blogspot.com/2009/05/in-depth-look-at-gridview-control.html</feedburner:origLink></entry><entry gd:etag="W/&quot;A0YBQn46cSp7ImA9WxJSFEw.&quot;"><id>tag:blogger.com,1999:blog-4074757583328233322.post-2995792078757104572</id><published>2009-05-03T21:45:00.000-07:00</published><updated>2009-05-03T23:39:13.019-07:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2009-05-03T23:39:13.019-07:00</app:edited><title>Encryption and Decryption Functions</title><content type="html">Microsoft provides very good classes for encryption and decryption under the following namespace.&lt;br /&gt;System.Security.Cryptography.&lt;br /&gt;Coding Sample Given as follows:&lt;br /&gt;&lt;br /&gt;using System;&lt;br /&gt;using System.Data;&lt;br /&gt;using System.Configuration;&lt;br /&gt;using System.Linq;&lt;br /&gt;using System.Web;&lt;br /&gt;using System.Web.Security;&lt;br /&gt;using System.Web.UI;&lt;br /&gt;using System.Web.UI.HtmlControls;&lt;br /&gt;using System.Web.UI.WebControls;&lt;br /&gt;using System.Web.UI.WebControls.WebParts;&lt;br /&gt;using System.Xml.Linq;&lt;br /&gt;using System.Text;&lt;br /&gt;using System.Text.RegularExpressions;&lt;br /&gt;using System.IO;&lt;br /&gt;using System.Security.Cryptography;&lt;br /&gt;&lt;br /&gt;/// &lt;summary&gt;&lt;br /&gt;/// Class which contains static reusable methods for encrypting a string.&lt;br /&gt;/// Mainly constructed for URL encryption but further can be used for string encryption&lt;br /&gt;/// needed in other operation.&lt;br /&gt;/// &lt;/summary&gt;&lt;br /&gt;public class Cryptex&lt;br /&gt;{&lt;br /&gt;public Cryptex()&lt;br /&gt;{&lt;br /&gt;//&lt;br /&gt;// TODO: Add constructor logic here&lt;br /&gt;//&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;internal static HttpServerUtility sUtil = HttpContext.Current.Server;&lt;br /&gt;&lt;br /&gt;/// &lt;summary&gt;&lt;br /&gt;/// Method used to encrypt a string making use of DES Algorithm.&lt;br /&gt;/// &lt;/summary&gt;&lt;br /&gt;/// &lt;param name="inputString"&gt;&lt;/param&gt;&lt;br /&gt;/// &lt;param name="key"&gt;&lt;/param&gt;&lt;br /&gt;/// &lt;returns&gt;&lt;/returns&gt;&lt;br /&gt;public static string StringEncrypt_DES(string queryString) {&lt;br /&gt;&lt;br /&gt;DESCryptoServiceProvider des = new DESCryptoServiceProvider();&lt;br /&gt;string key = ConfigurationManager.AppSettings["DESCryptokey"];&lt;br /&gt;&lt;br /&gt;des.Key = Encoding.UTF8.GetBytes(key.Substring(0, 8));&lt;br /&gt;des.IV = Encoding.UTF8.GetBytes(key.Substring(0, 8));&lt;br /&gt;ICryptoTransform cryptotransform = des.CreateEncryptor();&lt;br /&gt;try {&lt;br /&gt;MemoryStream mStream = new MemoryStream();&lt;br /&gt;CryptoStream cryptostream = new CryptoStream(mStream, cryptotransform, CryptoStreamMode.Write);&lt;br /&gt;StreamWriter writer = new StreamWriter(cryptostream);&lt;br /&gt;&lt;br /&gt;writer.WriteLine(queryString);&lt;br /&gt;writer.Close();&lt;br /&gt;cryptostream.Close();&lt;br /&gt;&lt;br /&gt;byte[] buffer = mStream.ToArray();&lt;br /&gt;mStream.Close();&lt;br /&gt;return Convert.ToBase64String(buffer);&lt;br /&gt;}&lt;br /&gt;catch {&lt;br /&gt;throw;&lt;br /&gt;}&lt;br /&gt;return string.Empty;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;/// &lt;summary&gt;&lt;br /&gt;/// Method used to dencrypt a string making use of DES Algorithm.&lt;br /&gt;/// &lt;/summary&gt;&lt;br /&gt;/// &lt;param name="inputString"&gt;&lt;/param&gt;&lt;br /&gt;/// &lt;param name="key"&gt;&lt;/param&gt;&lt;br /&gt;/// &lt;returns&gt;&lt;/returns&gt;&lt;br /&gt;public static string StringDecrypt_DES(string queryString) {&lt;br /&gt;&lt;br /&gt;DESCryptoServiceProvider des = new DESCryptoServiceProvider();&lt;br /&gt;string key = ConfigurationManager.AppSettings["DESCryptokey"];&lt;br /&gt;&lt;br /&gt;des.Key = Encoding.UTF8.GetBytes(key.Substring(0, 8));&lt;br /&gt;des.IV = Encoding.UTF8.GetBytes(key.Substring(0, 8));&lt;br /&gt;try {&lt;br /&gt;queryString = sUtil.UrlDecode(queryString);&lt;br /&gt;&lt;br /&gt;byte[] buffer = Convert.FromBase64String(queryString.Trim());&lt;br /&gt;&lt;br /&gt;MemoryStream mStream = new MemoryStream(buffer);&lt;br /&gt;ICryptoTransform cryptotransform = des.CreateDecryptor();&lt;br /&gt;CryptoStream cryptostream = new CryptoStream(mStream, cryptotransform, CryptoStreamMode.Read);&lt;br /&gt;&lt;br /&gt;StreamReader reader = new StreamReader(cryptostream);&lt;br /&gt;&lt;br /&gt;queryString = reader.ReadLine();&lt;br /&gt;reader.Close();&lt;br /&gt;cryptostream.Close();&lt;br /&gt;mStream.Close();&lt;br /&gt;}&lt;br /&gt;catch {&lt;br /&gt;throw;&lt;br /&gt;}&lt;br /&gt;return queryString;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;/// &lt;summary&gt;&lt;br /&gt;/// Method used to encrypt a string making use of RC2 Algorithm.&lt;br /&gt;/// &lt;/summary&gt;&lt;br /&gt;/// &lt;param name="inputString"&gt;&lt;/param&gt;&lt;br /&gt;/// &lt;param name="key"&gt;&lt;/param&gt;&lt;br /&gt;/// &lt;returns&gt;&lt;/returns&gt;&lt;br /&gt;public static string StringEncrypt_RC2(string inputString, string key) {&lt;br /&gt;&lt;br /&gt;RC2CryptoServiceProvider rc2 = new RC2CryptoServiceProvider();&lt;br /&gt;rc2.Mode = CipherMode.CBC;&lt;br /&gt;&lt;br /&gt;rc2.Key = ASCIIEncoding.ASCII.GetBytes(key);&lt;br /&gt;rc2.IV = ASCIIEncoding.ASCII.GetBytes(key);&lt;br /&gt;ICryptoTransform cryptotransform = rc2.CreateEncryptor();&lt;br /&gt;return encrypt(inputString, cryptotransform);&lt;br /&gt;}&lt;br /&gt;/// &lt;summary&gt;&lt;br /&gt;/// Method used to dencrypt a string making use of RC2 Algorithm.&lt;br /&gt;/// &lt;/summary&gt;&lt;br /&gt;/// &lt;param name="inputString"&gt;&lt;/param&gt;&lt;br /&gt;/// &lt;param name="key"&gt;&lt;/param&gt;&lt;br /&gt;/// &lt;returns&gt;&lt;/returns&gt;&lt;br /&gt;public static string StringDecrypt_RC2(string inputString, string key) {&lt;br /&gt;&lt;br /&gt;RC2CryptoServiceProvider rc2 = new RC2CryptoServiceProvider();&lt;br /&gt;rc2.Mode = CipherMode.CBC;&lt;br /&gt;&lt;br /&gt;rc2.Key = ASCIIEncoding.ASCII.GetBytes(key);&lt;br /&gt;rc2.IV = ASCIIEncoding.ASCII.GetBytes(key);&lt;br /&gt;ICryptoTransform cryptotransform = rc2.CreateDecryptor();&lt;br /&gt;return decrypt(inputString, cryptotransform);&lt;br /&gt;}&lt;br /&gt;/// &lt;summary&gt;&lt;br /&gt;/// Method used to encrypt a string making use of Rijndael Algorithm.&lt;br /&gt;/// &lt;/summary&gt;&lt;br /&gt;/// &lt;param name="inputString"&gt;&lt;/param&gt;&lt;br /&gt;/// &lt;param name="key"&gt;&lt;/param&gt;&lt;br /&gt;/// &lt;returns&gt;&lt;/returns&gt;&lt;br /&gt;public static string StringEncrypt_RIJNDAEL(string inputString, string key) {&lt;br /&gt;&lt;br /&gt;Rijndael rijndael = new RijndaelManaged();&lt;br /&gt;rijndael.Mode = CipherMode.CBC;&lt;br /&gt;rijndael.Key = ASCIIEncoding.ASCII.GetBytes(key);&lt;br /&gt;rijndael.IV = ASCIIEncoding.ASCII.GetBytes(key);&lt;br /&gt;ICryptoTransform cryptotransform = rijndael.CreateEncryptor();&lt;br /&gt;return encrypt(inputString, cryptotransform);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;/// &lt;summary&gt;&lt;br /&gt;/// Method used to dencrypt a string making use of Rijndael Algorithm.&lt;br /&gt;/// &lt;/summary&gt;&lt;br /&gt;/// &lt;param name="inputString"&gt;&lt;/param&gt;&lt;br /&gt;/// &lt;param name="key"&gt;&lt;/param&gt;&lt;br /&gt;/// &lt;returns&gt;&lt;/returns&gt;&lt;br /&gt;public static string StringDecrypt_RIJNDAEL(string inputString, string key) {&lt;br /&gt;&lt;br /&gt;Rijndael rijndael = new RijndaelManaged();&lt;br /&gt;rijndael.Mode = CipherMode.CBC;&lt;br /&gt;rijndael.Key = ASCIIEncoding.ASCII.GetBytes(key);&lt;br /&gt;rijndael.IV = ASCIIEncoding.ASCII.GetBytes(key);&lt;br /&gt;ICryptoTransform cryptotransform = rijndael.CreateDecryptor();&lt;br /&gt;return decrypt(inputString, cryptotransform);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;protected static string encrypt(string Str, ICryptoTransform cryptotransform) {&lt;br /&gt;try {&lt;br /&gt;MemoryStream mStream = new MemoryStream();&lt;br /&gt;CryptoStream cryptostream = new CryptoStream(mStream, cryptotransform, CryptoStreamMode.Write);&lt;br /&gt;StreamWriter writer = new StreamWriter(cryptostream);&lt;br /&gt;&lt;br /&gt;writer.WriteLine(Str.Trim());&lt;br /&gt;writer.Close();&lt;br /&gt;cryptostream.Close();&lt;br /&gt;&lt;br /&gt;byte[] buffer = mStream.ToArray();&lt;br /&gt;mStream.Close();&lt;br /&gt;Str = sUtil.UrlEncode(Convert.ToBase64String(buffer));&lt;br /&gt;}&lt;br /&gt;catch{&lt;br /&gt;throw;&lt;br /&gt;}&lt;br /&gt;return Str;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;protected static string decrypt(string Str, ICryptoTransform cryptotransform) {&lt;br /&gt;try {&lt;br /&gt;Str = sUtil.UrlDecode(Str.Trim());&lt;br /&gt;byte[] buffer = Convert.FromBase64String(Str);&lt;br /&gt;&lt;br /&gt;MemoryStream mStream = new MemoryStream(buffer);&lt;br /&gt;CryptoStream cryptostream = new CryptoStream(mStream, cryptotransform, CryptoStreamMode.Read);&lt;br /&gt;StreamReader reader = new StreamReader(cryptostream);&lt;br /&gt;Str = reader.ReadLine();&lt;br /&gt;reader.Close();&lt;br /&gt;cryptostream.Close();&lt;br /&gt;mStream.Close();&lt;br /&gt;}&lt;br /&gt;catch {&lt;br /&gt;throw;&lt;br /&gt;}&lt;br /&gt;return Str;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;const string DESKey = "AQWSEDRF";&lt;br /&gt;const string DESIV = "AQWSEDRF";&lt;br /&gt;&lt;br /&gt;public static string DESDecrypt(string stringToDecrypt)//Decrypt the content&lt;br /&gt;{&lt;br /&gt;byte[] key;&lt;br /&gt;byte[] IV;&lt;br /&gt;&lt;br /&gt;byte[] inputByteArray;&lt;br /&gt;try {&lt;br /&gt;key = Convert2ByteArray(DESKey);&lt;br /&gt;IV = Convert2ByteArray(DESIV);&lt;br /&gt;int len = stringToDecrypt.Length; inputByteArray = Convert.FromBase64String(stringToDecrypt);&lt;br /&gt;DESCryptoServiceProvider des = new DESCryptoServiceProvider();&lt;br /&gt;MemoryStream ms = new MemoryStream();&lt;br /&gt;CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(key, IV), CryptoStreamMode.Write);&lt;br /&gt;cs.Write(inputByteArray, 0, inputByteArray.Length);&lt;br /&gt;cs.FlushFinalBlock();&lt;br /&gt;Encoding encoding = Encoding.UTF8; return encoding.GetString(ms.ToArray());&lt;br /&gt;}&lt;br /&gt;catch (System.Exception ex) {&lt;br /&gt;throw ex;&lt;br /&gt;}&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;public static string DESEncrypt(string stringToEncrypt)// Encrypt the content&lt;br /&gt;{&lt;br /&gt;byte[] key;&lt;br /&gt;byte[] IV;&lt;br /&gt;&lt;br /&gt;byte[] inputByteArray;&lt;br /&gt;try {&lt;br /&gt;key = Convert2ByteArray(DESKey);&lt;br /&gt;IV = Convert2ByteArray(DESIV);&lt;br /&gt;inputByteArray = Encoding.UTF8.GetBytes(stringToEncrypt);&lt;br /&gt;DESCryptoServiceProvider des = new DESCryptoServiceProvider();&lt;br /&gt;MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(key, IV), CryptoStreamMode.Write);&lt;br /&gt;cs.Write(inputByteArray, 0, inputByteArray.Length);&lt;br /&gt;cs.FlushFinalBlock();&lt;br /&gt;return Convert.ToBase64String(ms.ToArray());&lt;br /&gt;}&lt;br /&gt;catch (System.Exception ex) {&lt;br /&gt;throw ex;&lt;br /&gt;}&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;static byte[] Convert2ByteArray(string strInput) {&lt;br /&gt;&lt;br /&gt;int intCounter; char[] arrChar;&lt;br /&gt;arrChar = strInput.ToCharArray();&lt;br /&gt;byte[] arrByte = new byte[arrChar.Length];&lt;br /&gt;for (intCounter = 0; intCounter &lt;= arrByte.Length - 1; intCounter++)&lt;br /&gt;arrByte[intCounter] = Convert.ToByte(arrChar[intCounter]);&lt;br /&gt;return arrByte;&lt;br /&gt;}&lt;br /&gt;}&lt;br /&gt;&lt;br&gt;&lt;br/&gt;&lt;br /&gt;For More Info Follow Following Link :&lt;br /&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.asnencodeddataenumerator.aspx"&gt;&lt;br /&gt;http://msdn.microsoft.com/en-us/library/system.security.cryptography.asnencodeddataenumerator.aspx&lt;br /&gt;&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4074757583328233322-2995792078757104572?l=apsdians.blogspot.com' alt='' /&gt;&lt;/div&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/ovl2MZJSgTHAmMxyCoKdmp1SDgM/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/ovl2MZJSgTHAmMxyCoKdmp1SDgM/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/ovl2MZJSgTHAmMxyCoKdmp1SDgM/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/ovl2MZJSgTHAmMxyCoKdmp1SDgM/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/ApsdiansBlog/~4/KElpkSv_JBw" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://apsdians.blogspot.com/feeds/2995792078757104572/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://apsdians.blogspot.com/2009/05/encryption-and-decryption-functions.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/4074757583328233322/posts/default/2995792078757104572?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/4074757583328233322/posts/default/2995792078757104572?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/ApsdiansBlog/~3/KElpkSv_JBw/encryption-and-decryption-functions.html" title="Encryption and Decryption Functions" /><author><name>Manoj Chavan</name><uri>http://www.blogger.com/profile/10656208957677029383</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="31" src="http://2.bp.blogspot.com/_pwedvTzC2Ig/SiNxe2TBDtI/AAAAAAAAAE0/vSjJtAmr3GI/S220/man.jpg" /></author><thr:total>0</thr:total><feedburner:origLink>http://apsdians.blogspot.com/2009/05/encryption-and-decryption-functions.html</feedburner:origLink></entry><entry gd:etag="W/&quot;Ak4NQHg9fyp7ImA9WxVUFUg.&quot;"><id>tag:blogger.com,1999:blog-4074757583328233322.post-4960797984674703045</id><published>2009-03-20T06:31:00.000-07:00</published><updated>2009-03-20T07:23:11.667-07:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2009-03-20T07:23:11.667-07:00</app:edited><title>Read Excel Database using ADO.Net</title><content type="html">&lt;p&gt;Excel is nothing but the other database only. It can be set like below&lt;br /&gt;The table example as follows :&lt;br /&gt;e.g. Student.xls&lt;br /&gt;Here&lt;br /&gt;-------------------------------------&lt;br /&gt;Database ---------------Table&lt;br /&gt;(Excel Workbook)------ (Excel Sheet)&lt;br /&gt;-------------------------------------&lt;br /&gt;Student.xls------------- personal_info&lt;br /&gt;-------------------------------------&lt;br /&gt;&lt;u&gt;id ------- Name -------- Address&lt;/u&gt;&lt;br /&gt;1 ------- Sachin -------- Patan&lt;br /&gt;2 ------- Sam ---------- New Lands &lt;/p&gt;&lt;p&gt;Now below given code gives you access for the excel database.&lt;/p&gt;&lt;p&gt;C# code snippet&lt;/p&gt;&lt;p&gt;-----------------------------&lt;br /&gt;using System;&lt;br /&gt;using System.Data;&lt;br /&gt;class Test{&lt;br /&gt;public static void Main(){&lt;br /&gt;IDbConnection con = new System.Data.Odbc.OdbcConnection("Driver={Microsoft Excel Driver (*.xls)};DBQ=db\\Student.xls"); &lt;/p&gt;&lt;p&gt;&lt;span style="color:#009900;"&gt;// The above line is for connection string.&lt;br /&gt;&lt;/span&gt;con.Open();&lt;br /&gt;IDbCommand cmd = con.CreateCommand();&lt;br /&gt;cmd.CommandText = "select id,name,address from [&lt;span style="color:#009900;"&gt;personal_info$&lt;/span&gt;]"; &lt;/p&gt;&lt;p&gt;&lt;span style="color:#009900;"&gt;//Here the personal_info$ is the worksheet i.e. (table) of Student.xls Workbook i.e. (Database).&lt;/span&gt;&lt;br /&gt;IDataReader reader = cmd.ExecuteReader();&lt;br /&gt;while(reader.Read()){&lt;br /&gt;Console.WriteLine("{0, -6}{1}{2}", reader.GetInt32(0), reader[1], reader["address"]); &lt;/p&gt;&lt;p&gt;&lt;span style="color:#009900;"&gt;// We can retrieve data with given three ways&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;span style="color:#009900;"&gt;// as reader.GetInt32(0) ----------&gt; Gives first field.&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;span style="color:#009900;"&gt;// reader[1] ------------------------&gt;Gives second field.&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;span style="color:#009900;"&gt;// reader["address"] ---------------&gt;Gives third field.&lt;/span&gt;&lt;br /&gt;}&lt;br /&gt;reader.Close();&lt;br /&gt;con.Close();&lt;br /&gt;}&lt;br /&gt;}&lt;br /&gt;&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4074757583328233322-4960797984674703045?l=apsdians.blogspot.com' alt='' /&gt;&lt;/div&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/eGWWz1pRVUwijSAa-14Yye21cPc/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/eGWWz1pRVUwijSAa-14Yye21cPc/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/eGWWz1pRVUwijSAa-14Yye21cPc/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/eGWWz1pRVUwijSAa-14Yye21cPc/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/ApsdiansBlog/~4/tQUo6jlzgC4" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://apsdians.blogspot.com/feeds/4960797984674703045/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://apsdians.blogspot.com/2009/03/read-excel-databse-using-adonet.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/4074757583328233322/posts/default/4960797984674703045?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/4074757583328233322/posts/default/4960797984674703045?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/ApsdiansBlog/~3/tQUo6jlzgC4/read-excel-databse-using-adonet.html" title="Read Excel Database using ADO.Net" /><author><name>Manoj Chavan</name><uri>http://www.blogger.com/profile/10656208957677029383</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="31" src="http://2.bp.blogspot.com/_pwedvTzC2Ig/SiNxe2TBDtI/AAAAAAAAAE0/vSjJtAmr3GI/S220/man.jpg" /></author><thr:total>0</thr:total><feedburner:origLink>http://apsdians.blogspot.com/2009/03/read-excel-databse-using-adonet.html</feedburner:origLink></entry><entry gd:etag="W/&quot;CkQHR3o9fCp7ImA9WxVUFUg.&quot;"><id>tag:blogger.com,1999:blog-4074757583328233322.post-4953915352578214523</id><published>2009-03-20T04:54:00.001-07:00</published><updated>2009-03-20T04:58:56.464-07:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2009-03-20T04:58:56.464-07:00</app:edited><title>Finding or Verifying Credit Card Numbers</title><content type="html">With a few simple regular expressions, you can easily verify whether your customer entered a valid credit card number on your order form. You can even determine the type of credit card being used. Each card issuer has its own range of card numbers, identified by the first 4 digits.&lt;br /&gt;&lt;br /&gt;You can use a slightly different regular expression to find credit card numbers, or number sequences that might be credit card numbers, within larger documents. This can be very useful to prove in a security audit that you're not improperly exposing your clients' financial details.&lt;br /&gt;&lt;br /&gt;We'll start with the order form.&lt;br /&gt;&lt;br /&gt;Stripping Spaces and Dashes&lt;br /&gt;The first step is to remove all non-digits from the card number entered by the customer. Physical credit cards have spaces within the card number to group the digits, making it easier for humans to read or type in. So your order form should accept card numbers with spaces or dashes in them.&lt;br /&gt;&lt;br /&gt;To remove all non-digits from the card number, simply use the "replace all" function in your scripting language to search for the regex [^0-9]+ and replace it with nothing. If you only want to replace spaces and dashes, you could use [ -]+. If this regex looks odd, remember that in a character class, the hyphen is a literal when it occurs right before the closing bracket (or right after the opening bracket or negating caret).&lt;br /&gt;&lt;br /&gt;If you're wondering what the plus is for: that's for performance. If the input has consecutive non-digits, e.g. 1===2, then the regex will match the three equals signs at once, and delete them in one replacement. Without the plus, three replacements would be required. In this case, the savings are only a few microseconds. But it's a good habit to keep regex efficiency in the back of your mind. Though the savings are minimal here, so is the effort of typing the extra plus.&lt;br /&gt;&lt;br /&gt;Validating Credit Card Numbers on Your Order Form&lt;br /&gt;Validating credit card numbers is the ideal job for regular expressions. They're just a sequence of 13 to 16 digits, with a few specific digits at the start that identify the card issuer. You can use the specific regular expressions below to alert customers when they try to use a kind of card you don't accept, or to route orders using different cards to different processors. All these regexes were taken from RegexBuddy's library.&lt;br /&gt;&lt;br /&gt;Visa: &lt;strong&gt;^4[0-9]{12}(?:[0-9]{3})?$&lt;/strong&gt;&lt;br /&gt;&lt;strong&gt;&lt;/strong&gt;&lt;br /&gt; All Visa card numbers start with a 4. New cards have 16 digits. Old cards have 13.&lt;br /&gt;&lt;br /&gt;MasterCard:&lt;strong&gt; ^5[1-5][0-9]{14}$&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt; All MasterCard numbers start with the numbers 51 through 55. All have 16 digits.&lt;br /&gt;&lt;br /&gt;American Express: &lt;strong&gt;^3[47][0-9]{13}$&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt; American Express card numbers start with 34 or 37 and have 15 digits.&lt;br /&gt;&lt;br /&gt;Diners Club:&lt;strong&gt; ^3(?:0[0-5][68][0-9])[0-9]{11}$ &lt;/strong&gt;&lt;br /&gt;&lt;strong&gt;&lt;/strong&gt;&lt;br /&gt;Diners Club card numbers begin with 300 through 305, 36 or 38. All have 14 digits. There are Diners Club cards that begin with 5 and have 16 digits. These are a joint venture between Diners Club and MasterCard, and should be processed like a MasterCard.&lt;br /&gt;&lt;br /&gt;Discover: &lt;strong&gt;^6(?:0115[0-9]{2})[0-9]{12}$ &lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;Discover card numbers begin with 6011 or 65. All have 16 digits.&lt;br /&gt;&lt;br /&gt;JCB: &lt;strong&gt;^(?:2131180035\d{3})\d{11}$&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt; JCB cards beginning with 2131 or 1800 have 15 digits. JCB cards beginning with 35 have 16 digits.&lt;br /&gt;If you just want to check whether the card number looks valid, without determining the brand, you can combine the above six regexes into&lt;br /&gt;&lt;strong&gt;^(?:4[0-9]{12}(?:[0-9]{3})?5[1-5][0-9]{14}6(?:0115[0-9][0-9])[0-9]{12}3[47][0-9]{13}3(?:0[0-5][68][0-9])[0-9]{11}(?:2131180035\d{3})\d{11})$.&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt; You'll see I've simply alternated all the regexes, and used a non-capturing group to put the anchors outside the alternation. You can easily delete the card types you don't accept from the list.&lt;br /&gt;&lt;br /&gt;These regular expressions will easily catch numbers that are invalid because the customer entered too many or too few digits. They won't catch numbers with incorrect digits. For that, you need to follow the Luhn algorithm, which cannot be done with a regex. And of course, even if the number is mathematically valid, that doesn't mean a card with this number was issued or if there's money in the account. The benefit or the regular expression is that you can put it in a bit of JavaScript to instantly check for obvious errors, instead of making the customer wait 30 seconds for your credit card processor to fail the order. And if your card processor charges for failed transactions, you'll really want to implement both the regex and the Luhn validation.&lt;br /&gt;&lt;br /&gt;Finding Credit Card Numbers in Documents&lt;br /&gt;With two simple modifications, you could use any of the above regexes to find card numbers in larger documents. Simply replace the caret and dollar with a word boundary,&lt;br /&gt;&lt;strong&gt;e.g.: \b4[0-9]{12}(?:[0-9]{3})?\b.&lt;br /&gt;&lt;/strong&gt;&lt;br /&gt;If you're planning to search a large document server, a simpler regular expression will speed up the search. Unless your company uses 16-digit numbers for other purposes, you'll have few false positives. The regex \b\d{13,16}\b will find any sequence of 13 to 16 digits.&lt;br /&gt;&lt;br /&gt;When searching a hard disk full of files, you can't strip out spaces and dashes first like you can when validating a single card number. To find card numbers with spaces or dashes in them, use \b(?:\d[ -]*){13,16}\b. This regex allows any amount of spaces and dashes anywhere in the number. This is really the only way. Visa and MasterCard put digits in sets of 4, while Amex and Discover use groups of 4, 5 and 6 digits. People typing in the numbers may have different ideas yet.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4074757583328233322-4953915352578214523?l=apsdians.blogspot.com' alt='' /&gt;&lt;/div&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/DgaLgpNG5CmlLm7A6y9z2Wt5EdU/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/DgaLgpNG5CmlLm7A6y9z2Wt5EdU/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/DgaLgpNG5CmlLm7A6y9z2Wt5EdU/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/DgaLgpNG5CmlLm7A6y9z2Wt5EdU/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/ApsdiansBlog/~4/o2dthrQG1tE" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://apsdians.blogspot.com/feeds/4953915352578214523/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://apsdians.blogspot.com/2009/03/finding-or-verifying-credit-card.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/4074757583328233322/posts/default/4953915352578214523?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/4074757583328233322/posts/default/4953915352578214523?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/ApsdiansBlog/~3/o2dthrQG1tE/finding-or-verifying-credit-card.html" title="Finding or Verifying Credit Card Numbers" /><author><name>Manoj Chavan</name><uri>http://www.blogger.com/profile/10656208957677029383</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="31" src="http://2.bp.blogspot.com/_pwedvTzC2Ig/SiNxe2TBDtI/AAAAAAAAAE0/vSjJtAmr3GI/S220/man.jpg" /></author><thr:total>0</thr:total><feedburner:origLink>http://apsdians.blogspot.com/2009/03/finding-or-verifying-credit-card.html</feedburner:origLink></entry><entry gd:etag="W/&quot;CUABQnY4eyp7ImA9WxVUFUk.&quot;"><id>tag:blogger.com,1999:blog-4074757583328233322.post-4698513032348608921</id><published>2009-03-20T02:46:00.000-07:00</published><updated>2009-03-20T03:09:13.833-07:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2009-03-20T03:09:13.833-07:00</app:edited><title>MVC Pattern of .NET</title><content type="html">&lt;script type="text/javascript"&gt;&lt;br /&gt;var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");&lt;br /&gt;document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));&lt;br /&gt;&lt;/script&gt;&lt;br /&gt;&lt;script type="text/javascript"&gt;&lt;br /&gt;try {&lt;br /&gt;var pageTracker = _gat._getTracker("UA-8003622-1");&lt;br /&gt;pageTracker._trackPageview();&lt;br /&gt;} catch(err) {}&lt;/script&gt;&lt;br /&gt;&lt;a href="http://1.bp.blogspot.com/_pwedvTzC2Ig/ScNoIs8hgaI/AAAAAAAAAAM/9CWvcmkULbY/s1600-h/mvc.JPG"&gt;&lt;img style="float:left; margin:0 10px 10px 0;cursor:pointer; cursor:hand;width: 223px; height: 145px;" src="http://1.bp.blogspot.com/_pwedvTzC2Ig/ScNoIs8hgaI/AAAAAAAAAAM/9CWvcmkULbY/s320/mvc.JPG" border="0" alt=""id="BLOGGER_PHOTO_ID_5315206483940573602" /&gt;&lt;/a&gt;&lt;br /&gt;The Model-View-Controller (MVC) architectural pattern separates an application into three main components: the model, the view, and the controller. The ASP.NET MVC framework provides an alternative to the ASP.NET Web Forms pattern for creating MVC-based Web applications. The ASP.NET MVC framework is a lightweight, highly testable presentation framework that (as with Web Forms-based applications) is integrated with existing ASP.NET features, such as master pages and membership-based authentication. The MVC framework is defined in the System.Web.Mvc namespace and is a fundamental, supported part of the System.Web namespace. &lt;br /&gt;&lt;br /&gt;MVC is a standard design pattern that many developers are familiar with. Some types of Web applications will benefit from the MVC framework. Others will continue to use the traditional ASP.NET application pattern that is based on Web Forms and postbacks. Other types of Web applications will combine the two approaches; neither approach excludes the other. &lt;br /&gt;&lt;br /&gt;The MVC framework includes the following components:&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Figure 01: Invoking a controller action that expects a parameter value (Click to view full-size image)&lt;br /&gt;• Models. Model objects are the parts of the application that implement the logic for the application's data domain. Often, model objects retrieve and store model state in a database. For example, a Product object might retrieve information from a database, operate on it, and then write updated information back to a Products table in SQL Server. &lt;br /&gt;&lt;br /&gt;In small applications, the model is often a conceptual separation instead of a physical one. For example, if the application only reads a data set and sends it to the view, the application does not have a physical model layer and associated classes. In that case, the data set takes on the role of a model object. &lt;br /&gt;• Views. Views are the components that display the application's user interface (UI). Typically, this UI is created from the model data. An example would be an edit view of a Products table that displays text boxes, drop-down lists, and check boxes based on the current state of a Products object. &lt;br /&gt;&lt;br /&gt;• Controllers. Controllers are the components that handle user interaction, work with the model, and ultimately select a view to render that displays UI. In an MVC application, the view only displays information; the controller handles and responds to user input and interaction. For example, the controller handles query-string values, and passes these values to the model, which in turn queries the database by using the values. &lt;br /&gt;&lt;br /&gt;The MVC pattern helps you create applications that separate the different aspects of the application (input logic, business logic, and UI logic), while providing a loose coupling between these elements. The pattern specifies where each kind of logic should be located in the application. The UI logic belongs in the view. Input logic belongs in the controller. Business logic belongs in the model. This separation helps you manage complexity when you build an application, because it enables you to focus on one aspect of the implementation at a time. For example, you can focus on the view without depending on the business logic. &lt;br /&gt;&lt;br /&gt;In addition to managing complexity, the MVC pattern makes it easier to test applications than it is to test a Web Forms-based ASP.NET Web application. For example, in a Web Forms-based ASP.NET Web application, a single class is used both to display output and to respond to user input. Writing automated tests for Web Forms-based ASP.NET applications can be complex, because to test an individual page, you must instantiate the page class, all its child controls, and additional dependent classes in the application. Because so many classes are instantiated to run the page, it can be hard to write tests that focus exclusively on individual parts of the application. Tests for Web Forms-based ASP.NET applications can therefore be more difficult to implement than tests in an MVC application. Moreover, tests in a Web Forms-based ASP.NET application require a Web server. The MVC framework decouples the components and makes heavy use of interfaces, which makes it possible to test individual components in isolation from the rest of the framework. &lt;br /&gt;&lt;br /&gt;The loose coupling between the three main components of an MVC application also promotes parallel development. For instance, one developer can work on the view, a second developer can work on the controller logic, and a third developer can focus on the business logic in the model. &lt;br /&gt;Deciding When to Create an MVC Application&lt;br /&gt;You must consider carefully whether to implement a Web application by using either the ASP.NET MVC framework or the ASP.NET Web Forms model. The MVC framework does not replace the Web Forms model; you can use either framework for Web applications. (If you have existing Web Forms-based applications, these continue to work exactly as they always have.) &lt;br /&gt;&lt;br /&gt;Before you decide to use the MVC framework or the Web Forms model for a specific Web site, weigh the advantages of each approach. &lt;br /&gt;Advantages of an MVC-Based Web Application&lt;br /&gt;The ASP.NET MVC framework offers the following advantages:&lt;br /&gt;• It makes it easier to manage complexity by dividing an application into the model, the view, and the controller. &lt;br /&gt;• It does not use view state or server-based forms. This makes the MVC framework ideal for developers who want full control over the behavior of an application. &lt;br /&gt;• It uses a Front Controller pattern that processes Web application requests through a single controller. This enables you to design an application that supports a rich routing infrastructure. For more information, see Front Controller on the MSDN Web site. &lt;br /&gt;• It provides better support for test-driven development (TDD). &lt;br /&gt;• It works well for Web applications that are supported by large teams of developers and Web designers who need a high degree of control over the application behavior. &lt;br /&gt;&lt;br /&gt;Advantages of a Web Forms-Based Web Application&lt;br /&gt;The Web Forms-based framework offers the following advantages:&lt;br /&gt;• It supports an event model that preserves state over HTTP, which benefits line-of-business Web application development. The Web Forms-based application provides dozens of events that are supported in hundreds of server controls. &lt;br /&gt;• It uses a Page Controller pattern that adds functionality to individual pages. For more information, see Page Controller on the MSDN Web site. &lt;br /&gt;• It uses view state or server-based forms, which can make managing state information easier. &lt;br /&gt;• It works well for small teams of Web developers and designers who want to take advantage of the large number of components available for rapid application development. &lt;br /&gt;• In general, it is less complex for application development, because the components (the Page class, controls, and so on) are tightly integrated and usually require less code than the MVC model. &lt;br /&gt;Features of the ASP.NET MVC Framework&lt;br /&gt;The ASP.NET MVC framework provides the following features:&lt;br /&gt;• Separation of application tasks (input logic, business logic, and UI logic), testability, and test-driven development (TDD) by default. All core contracts in the MVC framework are interface-based and can be tested by using mock objects, which are simulated objects that imitate the behavior of actual objects in the application. You can unit-test the application without having to run the controllers in an ASP.NET process, which makes unit testing fast and flexible. You can use any unit-testing framework that is compatible with the .NET Framework. &lt;br /&gt;• An extensible and pluggable framework. The components of the ASP.NET MVC framework are designed so that they can be easily replaced or customized. You can plug in your own view engine, URL routing policy, action-method parameter serialization, and other components. The ASP.NET MVC framework also supports the use of Dependency Injection (DI) and Inversion of Control (IOC) container models. DI allows you to inject objects into a class, instead of relying on the class to create the object itself. IOC specifies that if an object requires another object, the first objects should get the second object from an outside source such as a configuration file. This makes testing easier. &lt;br /&gt;• A powerful URL-mapping component that lets you build applications that have comprehensible and searchable URLs. URLs do not have to include file-name extensions, and are designed to support URL naming patterns that work well for search engine optimization (SEO) and representational state transfer (REST) addressing. &lt;br /&gt;• Support for using the markup in existing ASP.NET page (.aspx files), user control (.ascx files), and master page (.master files) markup files as view templates. You can use existing ASP.NET features with the ASP.NET MVC framework, such as nested master pages, in-line expressions (&lt;%= %&gt;), declarative server controls, templates, data-binding, localization, and so on. &lt;br /&gt;• Support for existing ASP.NET features. ASP.NET MVC lets you use features such as forms authentication and Windows authentication, URL authorization, membership and roles, output and data caching, session and profile state management, health monitoring, the configuration system, and the provider architecture.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4074757583328233322-4698513032348608921?l=apsdians.blogspot.com' alt='' /&gt;&lt;/div&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/xMdcRH4L3WySS1vGfY-BFQ_cpP8/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/xMdcRH4L3WySS1vGfY-BFQ_cpP8/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/xMdcRH4L3WySS1vGfY-BFQ_cpP8/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/xMdcRH4L3WySS1vGfY-BFQ_cpP8/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/ApsdiansBlog/~4/Jtl-XEpXaJk" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://apsdians.blogspot.com/feeds/4698513032348608921/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://apsdians.blogspot.com/2009/03/mvc-pattern-of-net.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/4074757583328233322/posts/default/4698513032348608921?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/4074757583328233322/posts/default/4698513032348608921?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/ApsdiansBlog/~3/Jtl-XEpXaJk/mvc-pattern-of-net.html" title="MVC Pattern of .NET" /><author><name>Manoj Chavan</name><uri>http://www.blogger.com/profile/10656208957677029383</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="31" src="http://2.bp.blogspot.com/_pwedvTzC2Ig/SiNxe2TBDtI/AAAAAAAAAE0/vSjJtAmr3GI/S220/man.jpg" /></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://1.bp.blogspot.com/_pwedvTzC2Ig/ScNoIs8hgaI/AAAAAAAAAAM/9CWvcmkULbY/s72-c/mvc.JPG" height="72" width="72" /><thr:total>0</thr:total><feedburner:origLink>http://apsdians.blogspot.com/2009/03/mvc-pattern-of-net.html</feedburner:origLink></entry><entry gd:etag="W/&quot;CUMDQHs9fip7ImA9WxVUFEo.&quot;"><id>tag:blogger.com,1999:blog-4074757583328233322.post-5549351035678515329</id><published>2009-03-19T07:28:00.000-07:00</published><updated>2009-03-19T07:37:51.566-07:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2009-03-19T07:37:51.566-07:00</app:edited><title>Building Secure ASP.NET Pages and Controls</title><content type="html">&lt;strong&gt;Threats and Countermeasures&lt;/strong&gt;&lt;br /&gt;Most Web application attacks require that malicious input is passed within HTTP requests. The general goal is either to coerce the application into performing unauthorized operations or to disrupt its normal operation. This is why thorough input validation is an essential countermeasure to many attacks and should be made a top priority when you develop ASP.NET Web pages and controls. Top threats include:&lt;br /&gt;Code injection&lt;br /&gt;Session hijacking&lt;br /&gt;Identity spoofing&lt;br /&gt;Parameter manipulation&lt;br /&gt;Network eavesdropping&lt;br /&gt;Information disclosure&lt;br /&gt;Figure 10.1 highlights the most common threats to Web applications.&lt;br /&gt;Figure 10.1&lt;br /&gt;Common threats to ASP.NET Web pages and controls&lt;br /&gt;Code Injection&lt;br /&gt;Code injection occurs when an attacker causes arbitrary code to run using your application's security context. The risk increases if your application runs using a privileged account.&lt;br /&gt;Attacks&lt;br /&gt;There are various types of code injection attacks. These include:&lt;br /&gt;Cross-site scripting. Malicious script is sent to a Web application as input. It is echoed back to a user's browser, where it is executed.&lt;br /&gt;Buffer overflows. The type safe verification of managed code reduces the risk significantly, but your application is still vulnerable, especially where it calls unmanaged code. Buffer overflows can allow an attacker to execute arbitrary code inside your Web application process, using its security context.&lt;br /&gt;SQL injection. This attack targets vulnerable data access code. The attacker sends SQL input that alters the intended query or executes completely new queries in the database. Forms authentication logon pages are common targets because the username and password are used to query the user store.&lt;br /&gt;Vulnerabilities&lt;br /&gt;Vulnerabilities that can lead to successful code injection attacks include:&lt;br /&gt;Weak or missing input validation or reliance on client-side input validation&lt;br /&gt;Including unvalidated input in HTML output&lt;br /&gt;Dynamically constructing SQL statements that do not use typed parameters&lt;br /&gt;Use of over-privileged process accounts and database logins&lt;br /&gt;Countermeasures&lt;br /&gt;The following countermeasures can be used to prevent code injection:&lt;br /&gt;Validate input so that an attacker cannot inject script code or cause buffer overflows.&lt;br /&gt;Encode all output that includes input. This prevents potentially malicious script tags from being interpreted as code by the client's browser.&lt;br /&gt;Use stored procedures that accept parameters to prevent malicious SQL input from being treated as executable statements by the database.&lt;br /&gt;Use least privileged process and impersonation accounts. This mitigates risk and reduces the damage that can be done if an attacker manages to execute code using the application's security context.&lt;br /&gt;Session Hijacking&lt;br /&gt;Session hijacking occurs when the attacker captures an authentication token and takes control of another user's session. Authentication tokens are often stored in cookies or in URLs. If the attacker captures the authentication token, he can transmit it to the application along with a request. The application associates the request with the legitimate user's session, which allows the attacker to gain access to the restricted areas of the application that require authenticated access. The attacker then assumes the identity and privileges of the legitimate user.&lt;br /&gt;Vulnerabilities&lt;br /&gt;Common vulnerabilities that make your Web pages and controls susceptible to session hijacking include:&lt;br /&gt;Unprotected session identifiers in URLs&lt;br /&gt;Mixing personalization cookies with authentication cookies&lt;br /&gt;Authentication cookies passed over unencrypted links&lt;br /&gt;Attacks&lt;br /&gt;Session hijacking attacks include:&lt;br /&gt;Cookie replay. The attacker captures the authentication cookie either by using network monitoring software or by some other means, for example, by exploiting an XSS scripting vulnerability.&lt;br /&gt;Query string manipulation. A malicious user changes the session identifier that is clearly visible in the URL query string.&lt;br /&gt;Countermeasures&lt;br /&gt;You can employ the following countermeasures to prevent session hijacking:&lt;br /&gt;Separate personalization and authentication cookies.&lt;br /&gt;Only transmit authentication cookies over HTTPS connections.&lt;br /&gt;Do not pass session identifiers that represent authenticated users in query strings.&lt;br /&gt;Re-authenticate the user before critical operations, such as order placement, money transfers, and so on, are performed.&lt;br /&gt;Identity Spoofing&lt;br /&gt;Identity spoofing occurs when a malicious user assumes the identity of a legitimate user so that he can access the application.&lt;br /&gt;Vulnerabilities&lt;br /&gt;Common vulnerabilities that make your Web pages and controls susceptible to an identity spoofing attack include:&lt;br /&gt;Authentication credentials that are passed over unencrypted links&lt;br /&gt;Authentication cookies that are passed over unencrypted links&lt;br /&gt;Weak passwords and policies&lt;br /&gt;Weak credential storage in the user store&lt;br /&gt;Attacks&lt;br /&gt;Identity spoofing attacks include:&lt;br /&gt;Cookie replay. The attacker steals the authentication cookie either by using network monitoring software or by using an XSS attack. The attacker then sends the cookie to the application to gain spoofed access.&lt;br /&gt;Brute force password attacks. The attacker repeatedly tries username and password combinations.&lt;br /&gt;Dictionary attacks. In this automated form of a brute force password attack, every word in a dictionary is tried as a password.&lt;br /&gt;Countermeasures&lt;br /&gt;You can employ the following countermeasures to prevent identity spoofing:&lt;br /&gt;Only transmit authentication credentials and cookies over HTTPS connections.&lt;br /&gt;Enforce strong passwords. Regular expressions can be used to ensure that user-supplied passwords meet suitable complexity requirements.&lt;br /&gt;Store password verifiers in the database. Store non-reversible password hashes combined with a random salt value to mitigate the risk of dictionary attacks.&lt;br /&gt;For more information about storing password hashes and other secrets in the database, see Chapter 14, "&lt;a id="ctl00_rs1_mainContentContainer_ctl04" onclick="javascript:Track('ctl00_rs1_mainContentContainer_ctl00ctl00_rs1_mainContentContainer_ctl04',this);" href="http://msdn.microsoft.com/en-us/library/aa302430.aspx"&gt;Building Secure Data Access&lt;/a&gt;."&lt;br /&gt;Parameter Manipulation&lt;br /&gt;Parameters are the items of data that are passed from the client to the server over the network. They include form fields, query strings, view state, cookies, and HTTP headers. If sensitive data or data that is used to make security decisions on the server are passed using unprotected parameters, your application is potentially vulnerable to information disclosure or unauthorized access.&lt;br /&gt;Vulnerabilities&lt;br /&gt;Vulnerabilities that can lead to parameter manipulation include:&lt;br /&gt;Using hidden form fields or query strings that contain sensitive data&lt;br /&gt;Passing cookies that contain security-sensitive data over unencrypted connections&lt;br /&gt;Attacks&lt;br /&gt;Parameter manipulation attacks include:&lt;br /&gt;Cookie replay attacks. The attacker captures and alters a cookie and then replays it to the application. This can easily lead to identity spoofing and elevation or privileges if the cookie contains data that is used for authentication or authorization on the server.&lt;br /&gt;Manipulation of hidden form fields. These fields contain data used for security decisions on the server.&lt;br /&gt;Manipulation of query string parameters.&lt;br /&gt;Countermeasures&lt;br /&gt;You can employ the following countermeasures to prevent parameter manipulation:&lt;br /&gt;Do not rely on client-side state management options. Avoid using any of the client-side state management options such as view state, cookies, query strings or hidden form fields to store sensitive data.&lt;br /&gt;Store sensitive data on the server. Use a session token to associate the user's session with sensitive data items that are maintained on the server.&lt;br /&gt;Use a message authentication code (MAC) to protect the session token. Pair this with authentication, authorization, and business logic on the server to ensure that the token is not being replayed.&lt;br /&gt;Network Eavesdropping&lt;br /&gt;Network eavesdropping involves using network monitoring software to trace packets of data sent between browser and Web server. This can lead to the disclosure of application-specific confidential data, the retrieval of logon credentials, or the capture of authentication cookies.&lt;br /&gt;Vulnerabilities&lt;br /&gt;Vulnerabilities that can lead to successful network eavesdropping include:&lt;br /&gt;Lack of encryption when sending sensitive data&lt;br /&gt;Sending authentication cookies over unencrypted channels&lt;br /&gt;Attacks&lt;br /&gt;Network eavesdropping attacks are performed by using packet sniffing tools that are placed on the network to capture traffic.&lt;br /&gt;Countermeasures&lt;br /&gt;To counter network eavesdropping, use Secure Sockets Layer (SSL) to provide an encrypted communication channel between browser and Web server. It is imperative that SSL is used whenever credentials, authentication tickets, or sensitive application data are sent over the network.&lt;br /&gt;Information Disclosure&lt;br /&gt;Information disclosure occurs when an attacker probes your Web pages looking for ways to cause exception conditions. This can be a fruitful exercise for the attacker because exception details, which often are returned as HTML and displayed in the browser, can divulge extremely useful information, such as stack traces that contain database connection strings, database names, database schema information, SQL statements, and operating system and platform versions.&lt;br /&gt;Vulnerabilities&lt;br /&gt;Vulnerabilities that lead to information disclosure include:&lt;br /&gt;Weak exception handling&lt;br /&gt;Letting raw exception details propagate to the client&lt;br /&gt;Attacks&lt;br /&gt;There are many attacks that can result in information disclosure. These include:&lt;br /&gt;Buffer overflows.&lt;br /&gt;Sending deliberately malformed input.&lt;br /&gt;Countermeasures&lt;br /&gt;To prevent information disclosure:&lt;br /&gt;Use structured exception handling.&lt;br /&gt;Return generic error pages to the client.&lt;br /&gt;Use default redirect pages that contain generic and harmless error messages.&lt;br /&gt;&lt;a name="c10618429_005"&gt;&lt;/a&gt;Design Considerations&lt;br /&gt;Before you develop Web pages and controls, there are a number of important issues that you should consider at design time. The following are the key considerations:&lt;br /&gt;Use server-side input validation.&lt;br /&gt;Partition your Web site.&lt;br /&gt;Consider the identity that is used for resource access.&lt;br /&gt;Protect credentials and authentication tickets.&lt;br /&gt;Fail securely.&lt;br /&gt;Consider authorization granularity.&lt;br /&gt;Place Web controls and user controls in separate assemblies.&lt;br /&gt;Place resource access code in a separate assembly.&lt;br /&gt;Use Server-Side Input Validation&lt;br /&gt;At design time, identify all the various sources of user input that your Web pages and controls process. This includes form fields, query strings, and cookies received from the Web user, as well as data from back-end data sources. The Web user clearly lives outside your application's trust boundary, so all of the input from that source must be validated at the server. Unless you can absolutely trust the data retrieved from back-end data sources, that data should also be validated and sanitized before it is sent to the client. Make sure your solution does not rely on client-side validation because this is easily bypassed.&lt;br /&gt;Partition Your Web Site&lt;br /&gt;Your Web site design should clearly differentiate between publicly accessible areas and restricted areas that require authenticated access. Use separate subdirectories beneath your application's virtual root directory to maintain restricted pages, such as checkout functionality in a classic e-commerce Web site that requires authenticated access and transmits sensitive data such as credit card numbers. Separate subdirectories allow you to apply additional security (for example, by requiring SSL) without incurring SSL performance overhead across the entire site. It also allows you to mitigate the risk of session hijacking by restricting the transmission of authentication cookies to HTTPS connections. Figure 10.2 shows a typical partitioning.&lt;br /&gt;Figure 10.2&lt;br /&gt;A Web site partitioned into public and secure areas&lt;br /&gt;Note that in Figure 10.2, the restricted subfolder is configured in Internet Information Services (IIS) to require SSL access. The first &lt;authorization&gt; element in Web.config allows all users to access the public area, while the second element prevents unauthenticated users from accessing the contents of the secured subfolder and forces a login.&lt;br /&gt;For more information about restricting authentication cookies so that they are passed only over HTTPS connections and about how to navigate between restricted and non-restricted pages, see "Use Absolute URLs for Navigation" in the "&lt;a href="http://msdn.microsoft.com/en-us/library/aa302426.aspx#c10618429_008"&gt;Authentication&lt;/a&gt;" section of this chapter.&lt;br /&gt;Consider the Identity That Is Used for Resource Access&lt;br /&gt;By default, ASP.NET applications do not impersonate, and the least privileged ASP.NET process account is used to run ASP.NET Web applications and for resource access. The default is the recommended configuration. There are several situations in which you may want to use a different Windows security context for resource access. These include:&lt;br /&gt;Hosting multiple applications on the same server&lt;br /&gt;You can use IIS to configure each application to use a separate anonymous Internet user account and then enable impersonation. Each application then has a distinct identity for resource access. For more information about this approach, see Chapter 20, "&lt;a id="ctl00_rs1_mainContentContainer_ctl05" onclick="javascript:Track('ctl00_rs1_mainContentContainer_ctl00ctl00_rs1_mainContentContainer_ctl05',this);" href="http://msdn.microsoft.com/en-us/library/aa302436.aspx"&gt;Hosting Multiple ASP.NET Applications&lt;/a&gt;."&lt;br /&gt;Note If your applications run on Windows Server 2003 with IIS 6.0, you can use application pools and configure each application to run in its own worker process that provides process-level isolation. By default, all applications run in a default application pool. With application pools, you can configure each process to run using a separate identity and, as a result, you do not need to use impersonation. For more information, see "&lt;a id="ctl00_rs1_mainContentContainer_ctl06" onclick="javascript:Track('ctl00_rs1_mainContentContainer_ctl00ctl00_rs1_mainContentContainer_ctl06',this);" href="http://msdn.microsoft.com/library/en-us/dnpag2/html/PAGHT000029.asp"&gt;How To: Improve Security When Hosting Multiple Applications in ASP.NET 2.0&lt;/a&gt;."&lt;br /&gt;Accessing a remote resource with specific authentication requirements&lt;br /&gt;If you need to access a specific remote resource (for example, a file share) and have been given a particular Windows account to use, you can use configure this account as the anonymous Web user account for your application. Then you can use programmatic impersonation prior to accessing the specific remote resource. For more information, see "&lt;a href="http://msdn.microsoft.com/en-us/library/aa302426.aspx#c10618429_010"&gt;Impersonation&lt;/a&gt;" later in this chapter.&lt;br /&gt;Protect Credentials and Authentication Tickets&lt;br /&gt;Your design should factor in how to protect credentials and authentication tickets. Credentials need to be secured if they are passed across the network and while they are in persistent stores such as configuration files. Authentication tickets must be secured over the network because they are vulnerable to hijacking. Encryption provides a solution. SSL or IPSec can be used to protect credentials and tickets over the network and DPAPI provides a good solution for encrypting credentials in configuration files.&lt;br /&gt;Fail Securely&lt;br /&gt;If your application fails with an unrecoverable exception condition, make sure that it fails securely and does not leave the system wide open. Make sure the exception details that are valuable to a malicious user are not allowed to propagate to the client and that generic error pages are returned instead. Plan to handle errors using structured exception handling, rather than relying on method error codes.&lt;br /&gt;Consider Authorization Granularity&lt;br /&gt;Consider the authorization granularity that you use in the authenticated parts of your site. If you have configured a directory to require authentication, should all users have equal access to the pages in that directory? If necessary, you can apply different authorization rules for separate pages based on the identity, or more commonly, the role membership of the caller, by using multiple &lt;authorization&gt; elements within separate &lt;location&gt; elements.&lt;br /&gt;For example, two pages in the same directory can have different &lt;allow&gt; and &lt;deny&gt; elements in Web.config.&lt;br /&gt;Place Web Controls and User Controls in Separate Assemblies&lt;br /&gt;When Web controls and user controls are put in their own assemblies, you can configure security for each assembly independently by using code access security policy. This provides additional flexibility for the administrator and it means that you are not forced to grant extended permissions to all controls just to satisfy the requirements of a single control.&lt;br /&gt;Place Resource Access Code in a Separate Assembly&lt;br /&gt;Use separate assemblies and call them from your page classes rather than embedding resource access code in your page class event handlers. This provides greater flexibility for code access security policy and is particularly important for building partial-trust Web applications. For more information, see Chapter 9, "&lt;a id="ctl00_rs1_mainContentContainer_ctl07" onclick="javascript:Track('ctl00_rs1_mainContentContainer_ctl00ctl00_rs1_mainContentContainer_ctl07',this);" href="http://msdn.microsoft.com/en-us/library/aa302425.aspx"&gt;Using Code Access Security with ASP.NET&lt;/a&gt;."&lt;br /&gt;&lt;a name="c10618429_006"&gt;&lt;/a&gt;Input Validation&lt;br /&gt;If you make unfounded assumptions about the type, length, format, or range of input, your application is unlikely to be robust. Input validation can become a security issue if an attacker discovers that you have made unfounded assumptions. The attacker can then supply carefully crafted input that compromises your application. The misplaced trust of user input is one of the most common and devastating vulnerabilities in Web applications.&lt;br /&gt;Constrain, Then Sanitize&lt;br /&gt;Start by constraining input and check for known good data by validating for type, length, format, and range. Sometimes you also need to sanitize input and make potentially malicious input safe. For example, if your application supports free-format input fields, such as comment fields, you might want to permit certain "safe" HTML elements, such as and , and strip out any other HTML elements. The following table summarizes the options that are available for constraining and sanitizing data:&lt;br /&gt;Table 10.1 Options for Constraining and Sanitizing Data&lt;br /&gt;Requirement&lt;br /&gt;Options&lt;br /&gt;Type checks&lt;br /&gt;.NET Framework type system. Parse string data, convert to a strong type, and then handle FormatExceptions.&lt;br /&gt;Regular expressions. Use ASP.NET RegularExpressionValidator control or Regex class.&lt;br /&gt;Length checks&lt;br /&gt;Regular expressions&lt;br /&gt;String.Length property&lt;br /&gt;Format checks&lt;br /&gt;Regular expressions for pattern matching&lt;br /&gt;.NET Framework type system&lt;br /&gt;Range checks&lt;br /&gt;ASP.NET RangeValidator control (supports currency, date, integer, double, and string data)&lt;br /&gt;Typed data comparisons&lt;br /&gt;Regular Expressions&lt;br /&gt;You can use regular expressions to restrict the range of valid characters, to strip unwanted characters, and to perform length and format checks. You can constrain input format by defining patterns that the input must match. ASP.NET provides the RegularExpressionValidator control and the Regex class is available from the System.Text.RegularExpressions namespace.&lt;br /&gt;If you use the validator controls, validation succeeds if the control is empty. For mandatory fields, use a RequiredFieldValidator. Also, the regular expression validation implementation is slightly different on the client and server. On the client, the regular expression syntax of Microsoft JScript® development software is used. On the server, System.Text.RegularExpressions.Regex syntax is used. Since JScript regular expression syntax is a subset of System.Text.RegularExpressions.Regex syntax, it is recommended that JScript regular expression syntax be used to yield the same results on both the client and the server.&lt;br /&gt;For more information about the full range of ASP.NET validator controls, refer to the .NET Framework documentation.&lt;br /&gt;RegularExpressionValidator Control&lt;br /&gt;To validate Web form field input, you can use the RegularExpressionValidator control. Drag the control onto a Web form and set its ValidationExpression, ControlToValidate, and ErrorMessage properties.&lt;br /&gt;You can set the validation expression using the properties window in Microsoft Visual Studio .NET or you can set the property dynamically in the Page_Load event handler. The latter approach allows you to group together all of the regular expressions for all controls on the page.&lt;br /&gt;Regex Class&lt;br /&gt;If you use regular HTML controls with no runat="server" property (which rules out using the RegularExpressionValidator control), or you need to validate input from other sources such as query strings or cookies, you can use the Regex class either in your page class or in a validation helper method, possibly in a separate assembly. Some examples are shown later in this section.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4074757583328233322-5549351035678515329?l=apsdians.blogspot.com' alt='' /&gt;&lt;/div&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/oYTSheVOg97YZNzqsfwDUYLDEBg/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/oYTSheVOg97YZNzqsfwDUYLDEBg/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/oYTSheVOg97YZNzqsfwDUYLDEBg/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/oYTSheVOg97YZNzqsfwDUYLDEBg/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/ApsdiansBlog/~4/tbAfcgxODfo" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://apsdians.blogspot.com/feeds/5549351035678515329/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://apsdians.blogspot.com/2009/03/building-secure-aspnet-pages-and.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/4074757583328233322/posts/default/5549351035678515329?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/4074757583328233322/posts/default/5549351035678515329?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/ApsdiansBlog/~3/tbAfcgxODfo/building-secure-aspnet-pages-and.html" title="Building Secure ASP.NET Pages and Controls" /><author><name>Manoj Chavan</name><uri>http://www.blogger.com/profile/10656208957677029383</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="31" src="http://2.bp.blogspot.com/_pwedvTzC2Ig/SiNxe2TBDtI/AAAAAAAAAE0/vSjJtAmr3GI/S220/man.jpg" /></author><thr:total>0</thr:total><feedburner:origLink>http://apsdians.blogspot.com/2009/03/building-secure-aspnet-pages-and.html</feedburner:origLink></entry><entry gd:etag="W/&quot;CUQER3w-fSp7ImA9WxVUFEo.&quot;"><id>tag:blogger.com,1999:blog-4074757583328233322.post-5308918557253995068</id><published>2009-03-19T00:45:00.000-07:00</published><updated>2009-03-19T07:35:06.255-07:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2009-03-19T07:35:06.255-07:00</app:edited><title>Secure Your Web.config</title><content type="html">1. Custom Errors Disabled------------------------------ When you disable custom errors as shown below, ASP.NET provides a detailed error message to&lt;br /&gt;clients by default. &lt;customerrors mode="RemoteOnly"&gt;&lt;br /&gt;In itself, knowing the source of an error may not seem like a risk to application security, but&lt;br /&gt;consider this: the more information a hacker can gather about a Web site, the more likely it is that&lt;br /&gt;he will be able to successfully attack it. An error message can be a gold mine of information to an&lt;br /&gt;attacker. A default ASP.NET error message lists the specific versions of ASP.NET and the .NET&lt;br /&gt;framework which are being used by the Web server, as well as the type of exception that was thrown.&lt;br /&gt;Just knowing which Web-based applications are used (in this case ASP.NET) compromises application&lt;br /&gt;security by telling the attacker that the server is running a relatively recent version of Microsoft&lt;br /&gt;Windows and that Microsoft Internet Information Server (IIS) 6.0 or later is being used as the Web&lt;br /&gt;server. The type of exception thrown may also help the attacker to profile Web-based applications;&lt;br /&gt;for example, if a "SqlException" is thrown, then the attacker knows that the application is using&lt;br /&gt;some version of Microsoft SQL Server. You can build up application security to prevent such information leakage by modifying the mode&lt;br /&gt;attribute of the &lt;customerrors&gt;element to "On" or "RemoteOnly." This setting instructs Web-based&lt;br /&gt;applications to display a nondescript, generic error message when an unhandled exception is&lt;br /&gt;generated. Another way to circumvent this application security issue is to redirect the user to a&lt;br /&gt;new page when errors occur by setting the "defaultRedirect" attribute of the &lt;customerrors&gt;element.&lt;br /&gt;This approach can provide even better application security because the default generic error page&lt;br /&gt;still gives away too much information about the system (namely, that it's using a Web.config file,&lt;br /&gt;which reveals that the server is running ASP.NET).&lt;br /&gt;2. Leaving Tracing Enabled in Web-Based ApplicationsThe trace feature of ASP.NET is one of the most useful tools that you can use to ensure application&lt;br /&gt;security by debugging and profiling your Web-based applications. Unfortunately, it is also one of&lt;br /&gt;the most useful tools that a hacker can use to attack your Web-based applications if it is left&lt;br /&gt;enabled in a production environment.&lt;br /&gt;&lt;trace localonly="true" enabled="false"&gt;&lt;br /&gt;&lt;trace localonly="true" enabled="false"&gt;&lt;br /&gt;When the &lt;trace&gt;element is enabled for remote users of Web-based applications (localOnly="false"),&lt;br /&gt;any user can view an incredibly detailed list of recent requests to the application simply by&lt;br /&gt;browsing to the page "trace.axd." If a detailed exception message is like a gold mine to a hacker&lt;br /&gt;looking to circumvent application security, a trace log is like Fort Knox! A trace log presents a&lt;br /&gt;wealth of information: the .NET and ASP.NET versions that the server is running; a complete trace of&lt;br /&gt;all the page methods that the request caused, including their times of execution; the session state&lt;br /&gt;and application state keys; the request and response cookies; the complete set of request headers,&lt;br /&gt;form variables, and QueryString variables; and finally the complete set of server variables.&lt;br /&gt;A hacker looking for a way around application security would obviously find the form variable&lt;br /&gt;histories useful because these might include email addresses that could be harvested and sold to&lt;br /&gt;spammers, IDs and passwords that could be used to impersonate the user, or credit card and bank&lt;br /&gt;account numbers. Even the most innocent-looking piece of data in the trace collection can be&lt;br /&gt;dangerous in the wrong hands. For example, the "APPL_PHYSICAL_PATH" server variable, which contains&lt;br /&gt;the physical path of Web-based applications on the server, could help an attacker perform directory&lt;br /&gt;traversal attacks against the system.&lt;br /&gt;The best way to prevent a hacker from obtaining trace data from Web-based applications is to disable&lt;br /&gt;the trace viewer completely by setting the "enabled" attribute of the &lt;trace&gt;element to "false." If&lt;br /&gt;you have to have the trace viewer enabled, either to debug or to profile your application, then be&lt;br /&gt;sure to set the "localOnly" attribute of the &lt;trace&gt;element to "true." That allows users to access&lt;br /&gt;the trace viewer only from the Web server and disables viewing it from any remote machine,&lt;br /&gt;increasing your application security.&lt;br /&gt;3. Debugging EnabledDeploying Web-based applications in debug mode is a very common mistake. Virtually all Web-based&lt;br /&gt;applications require some debugging. Visual Studio 2005 will even automatically modify the&lt;br /&gt;Web.config file to allow debugging when you start to debug your application. And, since deploying&lt;br /&gt;ASP.NET applications is as simple as copying the files from the development folder into the&lt;br /&gt;deployment folder, it's easy to see how development configuration settings can accidentally make it&lt;br /&gt;into production, compromising application security&lt;compilation debug="false"&gt;&lt;compilation debug="false"&gt;&lt;br /&gt;Like the first two application security vulnerabilities described in this list, leaving debugging&lt;br /&gt;enabled is dangerous because you are providing inside information to end users who shouldn't have&lt;br /&gt;access to it, and who may use it to attack your Web-based applications. For example, if you have&lt;br /&gt;enabled debugging and disabled custom errors in your application, then any error message displayed&lt;br /&gt;to an end user of your Web-based applications will include not only the server information, a&lt;br /&gt;detailed exception message, and a stack trace, but also the actual source code of the page where the&lt;br /&gt;error occurred.&lt;br /&gt;Unfortunately, this configuration setting isn't the only way that source code might be displayed to&lt;br /&gt;the user. Here's a story that illustrates why developers shouldn't concentrate solely on one type of&lt;br /&gt;configuration setting to improve application security. In early versions of Microsoft's ASP.NET AJAX&lt;br /&gt;framework, some controls would return a stack trace with source code to the client browser whenever&lt;br /&gt;exceptions occurred. This behavior happened whenever debugging was enabled, regardless of the custom&lt;br /&gt;error setting in the configuration. So, even if you properly configured your Web-based applications&lt;br /&gt;to display non-descriptive messages when errors occurred, you could still have unexpectedly revealed&lt;br /&gt;your source code to your end users if you forgot to disable debugging.&lt;br /&gt;To disable debugging, set the value of the "debug" attribute of the &lt;compilation&gt;element to&lt;br /&gt;"false." This is the default value of the setting, but as we will see in part two of this article,&lt;br /&gt;it's safer to explicitly set the desired value rather than relying on the defaults to protect&lt;br /&gt;application security.&lt;br /&gt;4. Cookies Accessible through Client-Side ScriptIn Internet Explorer 6.0, Microsoft introduced a new cookie property called "HttpOnly." While you&lt;br /&gt;can set the property programmatically on a per-cookie basis, you also can set it globally in the&lt;br /&gt;site configuration.&lt;br /&gt;Any cookie marked with this property will be accessible only from server-side code, and not to any&lt;br /&gt;client-side scripting code like JavaScript or VBScript. This shielding of cookies from the client&lt;br /&gt;helps to protect Web-based applications from Cross-Site Scripting attacks. A hacker initiates a&lt;br /&gt;Cross-Site Scripting (also called CSS or XSS) attack by attempting to insert his own script code&lt;br /&gt;into the Web page to get around any application security in place. Any page that accepts input from&lt;br /&gt;a user and echoes that input back is potentially vulnerable. For example, a login page that prompts&lt;br /&gt;for a user name and password and then displays "Welcome back, &lt;username&gt;" on a successful login may&lt;br /&gt;be susceptible to an XSS attack.&lt;br /&gt;Message boards, forums, and wikis are also often vulnerable to application security issues. In these&lt;br /&gt;sites, legitimate users post their thoughts or opinions, which are then visible to all other&lt;br /&gt;visitors to the site. But an attacker, rather than posting about the current topic, will instead&lt;br /&gt;post a message such as "alert(document.cookie);&lt;br /&gt;&lt;br /&gt;". The message board now includes&lt;br /&gt;the attacker's script code in its page code-and the browser then interprets and executes it for&lt;br /&gt;future site visitors. Usually attackers use such script code to try to obtain the user's&lt;br /&gt;authentication token (usually stored in a cookie), which they could then use to impersonate the&lt;br /&gt;user. When cookies are marked with the "HttpOnly" property, their values are hidden from the client,&lt;br /&gt;so this attack will fail.&lt;br /&gt;As mentioned earlier, it is possible to enable "HttpOnly" programmatically on any individual cookie&lt;br /&gt;by setting the "HttpOnly" property of the "HttpCookie" object to "true." However, it is easier and&lt;br /&gt;more reliable to configure the application to automatically enable "HttpOnly" for all cookies. To do&lt;br /&gt;this, set the "httpOnlyCookies" attribute of the &lt;httpcookies&gt;element to "true."&lt;br /&gt;5. Cookieless Session State EnabledIn the initial 1.0 release of ASP.NET, you had no choice about how to transmit the session token&lt;br /&gt;between requests when your Web application needed to maintain session state: it was always stored in&lt;br /&gt;a cookie. Unfortunately, this meant that users who would not accept cookies could not use your&lt;br /&gt;application. So, in ASP.NET 1.1, Microsoft added support for cookieless session tokens via use of&lt;br /&gt;the "cookieless" setting.&lt;br /&gt;&lt;sessionstate cookieless="UseCookies"&gt;&lt;br /&gt;Web applications configured to use cookieless session state now stored the session token in the page&lt;br /&gt;URLs rather than a cookie. For example, the page URL might change from&lt;br /&gt;&lt;a href="http://myserver/MyApplication/default.aspx"&gt;http://myserver/MyApplication/default.aspx&lt;/a&gt; to&lt;br /&gt;&lt;a href="http://myserver/MyApplication/(123456789ABCDEFG)/default.aspx"&gt;http://myserver/MyApplication/(123456789ABCDEFG)/default.aspx&lt;/a&gt;. In this case, "123456789ABCDEFG"&lt;br /&gt;represents the current user's session token. A different user browsing the site at the same time&lt;br /&gt;would receive a completely different session token, resulting in a different URL, such as&lt;br /&gt;&lt;a href="http://myserver/MyApplication/(ZYXWVU987654321)/default.aspx"&gt;http://myserver/MyApplication/(ZYXWVU987654321)/default.aspx&lt;/a&gt;.&lt;br /&gt;While adding support for cookieless session state did improve the usability of ASP.NET Web&lt;br /&gt;applications for users who would not accept cookies, it also had the side effect of making those&lt;br /&gt;applications much more vulnerable to session hijacking attacks. Session hijacking is basically a&lt;br /&gt;form of identity theft wherein a hacker impersonates a legitimate user by stealing his session&lt;br /&gt;token. When the session token is transmitted in a cookie, and the request is made on a secure&lt;br /&gt;channel (that is, it uses SSL), the token is secure. However, when the session token is included as&lt;br /&gt;part of the URL, it is much easier for a hacker to find and steal it. By using a network monitoring&lt;br /&gt;tool (also known as a "sniffer") or by obtaining a recent request log, hijacking the user's session&lt;br /&gt;becomes a simple matter of browsing to the URL containing the stolen unique session token. The Web&lt;br /&gt;application has no way of knowing that this new request with session token "123456789ABCDEFG" is not&lt;br /&gt;coming from the original, legitimate user. It happily loads the corresponding session state and&lt;br /&gt;returns the response back to the hacker, who has now effectively impersonated the user.&lt;br /&gt;The most effective way to prevent these session hijacking attacks is to force your Web application&lt;br /&gt;to use cookies to store the session token. This is accomplished by setting the "cookieless"&lt;br /&gt;attribute of the &lt;sessionstate&gt;element to "UseCookies" or "false." But what about the users who do&lt;br /&gt;not accept cookies? Do you have to choose between making your application available to all users&lt;br /&gt;versus ensuring that it operates securely for all users? A compromise between the two is possible in&lt;br /&gt;ASP.NET 2.0. By setting the "cookieless" attribute to "AutoDetect," the application will store the&lt;br /&gt;session token in a cookie for users who accept them and in the URL for those who won't. This means&lt;br /&gt;that only the users who use cookieless tokens will still be vulnerable to session hijacking. That's&lt;br /&gt;often acceptable, given the alternative-that users who deny cookies wouldn't be able to use the&lt;br /&gt;application at all. It is ironic that many users disable cookies because of privacy concerns when&lt;br /&gt;doing so can actually make them more prone to attack.&lt;br /&gt;6. Cookieless Authentication Enabled&lt;br /&gt;Just as in the "Cookieless Session State Enabled" vulnerability discussed in part one, enabling&lt;br /&gt;cookieless authentication in your Web-based applications can lead to session hijacking and problems&lt;br /&gt;with application security.&lt;br /&gt;&lt;authentication mode="Forms"&gt;&lt;br /&gt;&lt;forms cookieless="UseCookies"&gt;&lt;br /&gt;When a session or authentication token appears in the request URL rather than in a secure cookie, an&lt;br /&gt;attacker with a network monitoring tool can get around application security, easily take over that&lt;br /&gt;session, and effectively impersonate a legitimate user. However, session hijacking has far more&lt;br /&gt;serious consequences for application security after a user has been authenticated. For example,&lt;br /&gt;online shopping sites generally utilize Web-based applications that allow users to browse without&lt;br /&gt;having to provide an ID and password. But when users are ready to make a purchase, or when they want&lt;br /&gt;to view their order status, they have to login and be authenticated by the system. After logging in,&lt;br /&gt;sites provide access to more sensitive data, such as a user's order history, billing address, and&lt;br /&gt;credit card number. Attackers hijacking this user's session before authentication can't usually&lt;br /&gt;obtain much useful information. But if the attacker hijacks the session after authentication, all&lt;br /&gt;that sensitive information could be compromised.&lt;br /&gt;The best way to prevent session hijacking with Web-based applications is to disable cookieless&lt;br /&gt;authentication and force the use of cookies for storing authentication tokens. This application&lt;br /&gt;security measure is added by changing the cookieless attribute of the forms element to the value&lt;br /&gt;UseCookies.&lt;br /&gt;7. Failure to Require SSL for Authentication Cookies&lt;br /&gt;Web-based applications use the Secure Sockets Layer (SSL) protocol to encrypt data passed between&lt;br /&gt;the Web server and the client. Using SSL for application security means that attackers using network&lt;br /&gt;sniffers will not be able to interpret the exchanged data. Rather than seeing plaintext requests and&lt;br /&gt;responses, they will see only an indecipherable jumble of meaningless characters.&lt;br /&gt;You can require the forms authentication cookie from your Web-based applications to use SSL by&lt;br /&gt;setting the requireSSL attribute of the forms element to true.&lt;br /&gt;&lt;forms requiressl="true"&gt;&lt;br /&gt;The previous section discussed the importance of transmitting the authentication token in a cookie,&lt;br /&gt;rather than embedding it in the request URL. However, disabling cookieless authentication is just&lt;br /&gt;the first step towards securing the authentication token. Unless requests made to the Web server are&lt;br /&gt;encrypted, a network sniffer will still be able to read the authentication token from the request&lt;br /&gt;cookie. An attacker would still be able to hijack the user's session.&lt;br /&gt;At this point, you might be wondering why it is necessary with application security to disable&lt;br /&gt;cookieless authentication, since it is very inconvenient for users who won't accept cookies, and&lt;br /&gt;seeing as how the request still has to be sent over SSL. The answer is that the request URL is often&lt;br /&gt;persisted regardless of whether or not it was sent via SSL. Most major browsers save the complete&lt;br /&gt;URL in the browser history cache. If the history cache were to be compromised, the user's login&lt;br /&gt;credentials would be as well. Therefore, to truly secure the authentication token, you must require&lt;br /&gt;the authentication token to be stored in a cookie, and use SSL to ensure that the cookie be&lt;br /&gt;transmitted securely.&lt;br /&gt;By setting the requireSSL attribute of the forms element to true, ASP.NET Web-based applications&lt;br /&gt;will use a secure connection when transmitting the authentication cookie to the Web server. Note&lt;br /&gt;that IIS requires additional configuration steps to support SSL. You can find instructions to&lt;br /&gt;configure SSL for IIS on MSDN&lt;br /&gt;(&lt;a href="http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/56bdf977-14f8-4867-9c51"&gt;http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/56bdf977-14f8-4867-9c51&lt;/a&gt;-&lt;br /&gt;34c346d48b04.mspx?mfr=true).&lt;br /&gt;8. Sliding Expiration Used&lt;br /&gt;All authenticated ASP.NET sessions have a timeout interval to protect the application security. The&lt;br /&gt;default timeout value is 30 minutes. So, 30 minutes after a user first logs into any of these&lt;br /&gt;Web-based applications, he will automatically be logged out and forced to re-authenticate his&lt;br /&gt;credentials.&lt;br /&gt;Vulnerable configuration:&lt;br /&gt;&lt;configuration&gt;&lt;br /&gt;&lt;system.web&gt;&lt;br /&gt;&lt;authentication mode="Forms"&gt;&lt;br /&gt;&lt;forms slidingexpiration="true"&gt;&lt;br /&gt;Secure configuration:&lt;br /&gt;&lt;configuration&gt;&lt;br /&gt;&lt;system.web&gt;&lt;br /&gt;&lt;authentication mode="Forms"&gt;&lt;br /&gt;&lt;forms slidingexpiration="false"&gt;&lt;br /&gt;The slidingExpiration setting is an application security measure used to reduce risk to Web-based&lt;br /&gt;applications in case the authentication token is stolen. When set to false, the specified timeout&lt;br /&gt;interval becomes a fixed period of time from the initial login, rather than a period of inactivity.&lt;br /&gt;Attackers using a stolen authentication token have, at maximum, only the specified length of time to&lt;br /&gt;impersonate the user before the session times out. Because typical attackers of these Web-based&lt;br /&gt;applications have only the token, and don't really know the user's credentials, they can't log back&lt;br /&gt;in as the legitimate user, so the stolen authentication token is now useless and the application&lt;br /&gt;security threat is mitigated. When sliding expiration is enabled, as long as an attacker makes at&lt;br /&gt;least one request to the system every 15 minutes (or half of the timeout interval), the session will&lt;br /&gt;remain open indefinitely. This gives attackers more opportunities to steal information and cause&lt;br /&gt;other mischief in Web-based applications.&lt;br /&gt;To avoid this application security issue altogether, you can disable sliding expiration by setting&lt;br /&gt;the slidingExpiration attribute of the forms element to false.&lt;br /&gt;9. Non-Unique Authentication Cookie Used&lt;br /&gt;Over the last few sections, I hope I have successfully demonstrated the importance of application&lt;br /&gt;security and of storing your application's authentication token in a secure cookie value. But a&lt;br /&gt;cookie is more than just a value; it is a name-value pair. As strange as it seems, an improperly&lt;br /&gt;chosen cookie name can create an application security vulnerability just as dangerous as an&lt;br /&gt;improperly chosen storage location.&lt;br /&gt;Vulnerable configuration:&lt;br /&gt;&lt;configuration&gt;&lt;br /&gt;&lt;system.web&gt;&lt;br /&gt;&lt;authentication mode="Forms"&gt;&lt;br /&gt;&lt;forms name=".ASPXAUTH"&gt;&lt;br /&gt;Secure configuration:&lt;br /&gt;&lt;configuration&gt;&lt;br /&gt;&lt;system.web&gt;&lt;br /&gt;&lt;authentication mode="Forms"&gt;&lt;br /&gt;&lt;forms name="{abcd1234…}"&gt;&lt;br /&gt;The default value for the name of the authentication cookie is .ASPXAUTH. If you have only one&lt;br /&gt;Web-based application on your server, then .ASPXAUTH is a perfectly secure choice for the cookie&lt;br /&gt;name. In fact, any choice would be secure. But, when your server runs multiple ASP.NET Web-based&lt;br /&gt;applications, it becomes critical to assign a unique authentication cookie name to each application.&lt;br /&gt;If the names are not unique, then users logging into any of the Web-based applications might&lt;br /&gt;inadvertently gain access to all of them. For example, a user logging into the online shopping site&lt;br /&gt;to view his order history might find that he is now able to access the administration application on&lt;br /&gt;the same site and change the prices of the items in his shopping cart.&lt;br /&gt;The best way to ensure that all Web-based applications on your server have their own set of&lt;br /&gt;authorized users is to change the authentication cookie name to a unique value. Globally Unique&lt;br /&gt;Identifiers (GUIDs) are excellent choices for application security since they are guaranteed to be&lt;br /&gt;unique. Microsoft Visual Studio helpfully includes a tool that will automatically generate a GUID&lt;br /&gt;for you. You can find this tool in the Tools menu with the command name "Create GUID". Copy the&lt;br /&gt;generated GUID into the name attribute of the forms element in the configuration file.&lt;br /&gt;10. Hardcoded Credentials Used&lt;br /&gt;&lt;authentication mode="Forms"&gt;&lt;br /&gt;&lt;forms&gt;&lt;br /&gt;&lt;/forms&gt;&lt;br /&gt;A fundamental difficulty of creating software is that the environment in which the application will&lt;br /&gt;be deployed is usually not the same environment in which it is created. In a production environment,&lt;br /&gt;the operating system may be different, the hardware on which the application runs may be more or&lt;br /&gt;less powerful, and test databases are replaced with live databases. This is an issue for creating&lt;br /&gt;Web-based applications that require authentication because developers and administrators often use&lt;br /&gt;test credentials to test the application security. This begs the question: Where do the test&lt;br /&gt;credentials come from?&lt;br /&gt;For convenience, to avoid forcing developers from spending time on creating a credential store used&lt;br /&gt;solely for test purposes (and which would subsequently be discarded when the application went to&lt;br /&gt;production), Microsoft added a section to the Web.config file that you can use to quickly add test&lt;br /&gt;users to Web-based applications. For each test user, the developer adds an element to the&lt;br /&gt;configuration file with the desired user ID and password as shown below:&lt;br /&gt;&lt;authentication mode="Forms"&gt;&lt;br /&gt;&lt;forms&gt;&lt;br /&gt;&lt;credentials&gt;&lt;br /&gt;&lt;user name="bob" password="bob"&gt;&lt;br /&gt;&lt;user name="jane" password="Elvis"&gt;&lt;br /&gt;&lt;/credentials&gt;&lt;br /&gt;&lt;/forms&gt;&lt;br /&gt;&lt;/authentication&gt;&lt;br /&gt;While undeniably convenient for development purposes, this was never intended for use in a&lt;br /&gt;production environment. Storing login credentials in plaintext in a configuration file is simply not&lt;br /&gt;secure. Anyone with read access to the Web.config file could access the authenticated Web&lt;br /&gt;application. It is possible to store the SHA-1 or MD5 hash of the password value, rather than&lt;br /&gt;storing the password in plaintext. This is somewhat better, but it is still not a secure solution.&lt;br /&gt;Using this method, the user name is still not encrypted. First, providing a known user name to a&lt;br /&gt;potential attacker makes it easier to perform a brute force attack against the system. Second, there&lt;br /&gt;are many reverse-lookup databases of SHA-1 and MD5 hash values available on the Internet. If the&lt;br /&gt;password is simple, such as a word found in a dictionary, then it is almost guaranteed to be found&lt;br /&gt;in one of these hash dictionaries.&lt;br /&gt;The most secure way to store login credentials is to not store them in the configuration file.&lt;br /&gt;Remove the credentials element from your Web.config files in production applications.&lt;br /&gt;You're Not Out of the Woods Yet&lt;br /&gt;Now that you've finished reading the top-ten list, and you've checked your configuration settings,&lt;br /&gt;your applications are secure forever, right? Not just yet. Web.config files operate in a&lt;br /&gt;hierarchical inheritance manner. Every Web.config file inherits values from any Web.config file in a&lt;br /&gt;parent directory. That Web.config file in turn inherits values from any Web.config file in its&lt;br /&gt;parent directory, and so on. All Web.config files on the system inherit from the global&lt;br /&gt;configuration file called Machine.config located in the .NET framework directory. The effect of this&lt;br /&gt;is that the runtime behavior of your application can be altered simply by modifying a configuration&lt;br /&gt;file in a higher directory.&lt;br /&gt;This can sometimes have unexpected consequences. A system administrator might make a change in a&lt;br /&gt;configuration file in response to a problem with a completely separate application, but that change&lt;br /&gt;might create a security vulnerability in your application. For example, a user might report that he&lt;br /&gt;is not able to access the application without enabling cookies in his browser. The administrator,&lt;br /&gt;trying to be helpful, modifies the global configuration file to allow cookieless authentication for&lt;br /&gt;all applications.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4074757583328233322-5308918557253995068?l=apsdians.blogspot.com' alt='' /&gt;&lt;/div&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/U1SK2GYpq5yG2b_b3kymABmHVgE/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/U1SK2GYpq5yG2b_b3kymABmHVgE/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/U1SK2GYpq5yG2b_b3kymABmHVgE/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/U1SK2GYpq5yG2b_b3kymABmHVgE/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/ApsdiansBlog/~4/1fgkhDzGdKk" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://apsdians.blogspot.com/feeds/5308918557253995068/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://apsdians.blogspot.com/2009/03/secure-your-webconfig.html#comment-form" title="1 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/4074757583328233322/posts/default/5308918557253995068?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/4074757583328233322/posts/default/5308918557253995068?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/ApsdiansBlog/~3/1fgkhDzGdKk/secure-your-webconfig.html" title="Secure Your Web.config" /><author><name>Manoj Chavan</name><uri>http://www.blogger.com/profile/10656208957677029383</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="31" src="http://2.bp.blogspot.com/_pwedvTzC2Ig/SiNxe2TBDtI/AAAAAAAAAE0/vSjJtAmr3GI/S220/man.jpg" /></author><thr:total>1</thr:total><feedburner:origLink>http://apsdians.blogspot.com/2009/03/secure-your-webconfig.html</feedburner:origLink></entry></feed>

