Saturday, April 20, 2013

Big Data

Big Data

Big data is a collection of data sets so large and complex that it becomes difficult to process using on-hand database management tools or traditional data processing applications. 

Friday, December 10, 2010

Linq

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.

Introduction to LINQ

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 class.

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.

Simple LINQ Example

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.

using System.Query;
using System.Data.DLinq;
using System.Xml.XLinq;

Out of the above namespaces, System.Query namespace is the core namespace that exposes standard LINQ query operators.

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:

private void btnLoopThroughStrings_Click(object sender, EventArgs e)
{
string[] names = {"John", "Peter", "Joe", "Patrick", "Donald", "Eric"};
IEnumerable namesWithFiveCharacters =
from name in names
where name.Length < 5
select name;
lstResults.Items.Clear();
foreach(var name in namesWithFiveCharacters)
lstResults.Items.Add(name);
}

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:

Let us walk through the code line by line.

First, you declare a string array called names.

string[] names = {"John", "Peter", "Joe", "Patrick", "Donald", "Eric"};

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.

IEnumerable namesWithFiveCharacters =
from name in names
where name.Length < 5
select name;

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.

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.

An In-Depth look at LINQ

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:

* Type Inference
* Lamda Expressions
* Extension Methods
* Anonymous Types

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.

Type Inference

To understand type inference, let us look at couple of lines of code.

var count = 1;
var output = "This is a string";
var employees = new EmployeesCollection();

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.

As an example, let us modify our string query example to use the var keyword.

private void btnLoopThroughStrings_Click(object sender, EventArgs e)
{
string[] names = {"John", "Peter", "Joe", "Patrick", "Donald", "Eric"};
var namesWithFiveCharacters =
from name in names
where name.Length < 5
select name'
lstResults.Items.Clear();
foreach(var name in namesWithFiveCharacters)
lstResults.Items.Add(name);
}

As the above code shows, the variable namesWithFiveCharacters now uses the type "var" instead of IEnumerable. 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, the compiler will automatically assume that it is a variable of type IEnumerable.

If you run the code, it still produces the same output.

Lambda Expressions

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:

public SimpleForm()
{
addButton = new Button(...);
addButton.Click += delegate
{
MessageBox.Show ("Button clicked");
};
}

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 "=>" 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,

employee => employee.StartsWith("D");

In this case, the delegates used in the above query are defined in the System.Query namespace as such:

public delegate T Func();
public delegate T Func(A0 arg0);

So this code snippet could be written as:

Func person = delegate (string s) {
return s.StartsWith("D"); };

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.

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:

(int count) => count + 1 //explicitly typed parameter
(y,z) => return y * z; //implicitly typed parameter

Extension Methods

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:

public static IEnumerable Where(
this IEnumerable source, Func predicate) {
foreach (T element in source) {
if (predicate(element)) yield return element;
}
}

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 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.

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:

public static class StringExtension
{
public static void Echo(this string s)
{
Console.WriteLine("Supplied string : " + s);
}
}

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.

string s = "Hello world";
s.Echo();

Based on the above code, here are the key characteristics of extension methods.

1. Extension methods have the keyword this before the first argument
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
3. Extension methods can be defined only in a static class
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.

Using Collections in LINQ

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:

public class Person
{
private string _firstName;
private string _lastName;
private string _address;

public Person(){}

public string FirstName
{
get { return _firstName; }
set{_firstName = value; }
}

public string LastName
{
get { return _lastName; }
set { _lastName = value; }
}

public string Address
{
get{return _address; }
set{ _address = value; }
}
}

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:

private void btnLoopThroughObjects_Click(object sender, EventArgs e)
{
List persons = new List
{new Person{FirstName = "Joe", LastName = "Adams", Address = "Chandler"},
new Person{FirstName = "Don", LastName ="Alexander", Address = "Washington"},
new Person{FirstName = "Dave", LastName = "Ashton", Address = "Seattle"},
new Person{FirstName = "Bill", LastName = "Pierce", Address = "Sacromento"},
new Person{FirstName = "Bill", LastName ="Giard", Address = "Camphill"}};
var personsNotInSeattle = from person in persons
where person.Address != "Seattle"
orderby person.FirstName
select person;
lstResults.Items.Clear();
foreach (var person in personsNotInSeattle)
{
lstResults.Items.Add(person.FirstName + " " + person.LastName +
" - " + person.Address);
}
}

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:

new Person{FirstName = "Dave", LastName = "Ashton", Address = "Seattle"}

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 collection, so can be used against any Generics or non-Generics based object collections you already have.

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.

var personsNotInSeattle = from person in persons
where person.Address != "Seattle"
orderby person.FirstName
select person;

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:

Anonymous Types

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.

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.

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.

private void btnLoopThroughAnonymous_Click(object sender, EventArgs e)
{
List persons = new List
{new Person{FirstName = "Joe", LastName = "Adams", Address = "Chandler"},
new Person{FirstName = "Don", LastName ="Alexander", Address = "Washington"},
new Person{FirstName = "Dave", LastName = "Ashton", Address = "Seattle"},
new Person{FirstName = "Bill", LastName = "Pierce", Address = "Sacromento"},
new Person{FirstName = "Bill", LastName ="Giard", Address = "Camphill"}};
var personsNotInSeattle = from person in persons
where person.Address != "Seattle"
orderby person.FirstName
select new {person.FirstName,
person.Address};
lstResults.Items.Clear();
foreach (var person in personsNotInSeattle)
{
lstResults.Items.Add(person.FirstName + " --- " + person.Address );
}
}

Before discussing the code in detail, here is the output produced by the above code.

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:

public class ?????
{
private string firstName;
private string address;

public string FirstName
{
get { return firstName; }
set { firstName= value; }
}

public string Address
{
get { return address; }
set { address = value; }
}
}

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 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.

DLinq and XLinq

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:

from c in customers
where c.LastName.StartsWith("A")
select c

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!

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:

from c in customerXml.Descendants("Customer")
where c.Element("LastName").Value.StartsWith("A")
select c

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.

Conclusion

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. 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.

Thursday, July 2, 2009

AJAX

hi....


VISIT THIS SITE HAVING FUN WITH VIDEOS ON AJAX :-

AJAX with www.asp.net/LEARN/ajax-videos/

Monday, May 25, 2009

Navigation From One Page to Another Page with Data.














Navigation From One Page to Another Page with Data.


There are various ways to send the data from one page to other

1> Using QueryString.

e.g.
In first page you can write as follows :

Response.Redirect("mypage.aspx?id=" + value from control or variable or anystring);
mypage.aspx?id=10


Above dummy my page now contains id as the query string
and
It can be retrieved on the other page as follows :

string id = Request.QueryString["id"].ToString();

2> Using Session.
e.g. You can create session in first page like.

Session["id"] = value from control or variable or anystring;
and you can retrive it from other page as following:

string id = Session["id"].ToString();

3>Using Cookies
e.g. You can write cookie as in first page as follows :

Response.Cookies["id"].Value = value from control or variable or anystring;
and to retrive cookie you can request it as follows:

string id = Request.Cookies["BackgroundColor"].Value.ToString();

Friday, May 22, 2009

Advanced Diploma in Software Development






Advanced Diploma in Software Development (ADSD)

About ADSD


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.



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.



Right from the Programming Languages & 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.




Programme Objective


This is a programme specially designed for all the graduates who want to make their career in the IT industry.

Are you eligible?


Successful completion of 10 + 2 + 3 or 4 or equivalent from a recognised University with minimum 50% at degree level.
Computer Science or IT Diploma holders from the recognised technical boards with 2 years of relevant IT experience can apply.


How can I apply?


1. Obtain Application Form and Prospectus, available at MET for Rs. 600/- in cash or DD payable at Mumbai in favour of
'MET ISDR'. You can also pay online (click here) and the same will be sent to you.
2. Fill the Application Form and submit the same with necessary documents (mentioned in the Prospectus).
3. Appear for the Selection Procedure on scheduled date.

Important Dates








1.

Last Date of Form Submission (Registration Closes) June 29, 2009
2.Entrance Exam and Selection Procedure July 05, 2009


Selection Procedure
Based on the performance in the MET CET (consisting of Written Test & Personal Interview).
Programme Modules
The ADSD programme is divided into two parts. Each part consists of four modules. Each module is divided into two units.
Following is the detailed structure:

























Part I - Systems Programming

Part II - Application Programming


Module 1: Programming Foundations

Unit 1: Assembly and C Programming

Unit 2: C++ Programming

Module 5: Web Programming

Unit 1: The Client Side

Unit 2: The Server Side


Module 2: Linux System Programming

Unit 1: The Kernel

Unit 2: The Shell


Module 6: Java Programming

Unit 1: Desktop Java

Unit 2: Distributed Java


Module 3: Windows System Programming

Unit 1: WIN32 Platform SDK

Unit 2: MFC and COM


Module 7: .NET Programming

Unit 1: Desktop .NET

Unit 2: Distributed .NET


Module 4: SE & Project Management
Unit 1: Software Engineering
Unit 2: Project Management


Module 8: Aptitude Skills, Communications & Personality Development
Unit 1: Aptitude Skills
Unit 2: Communications & Personality Development



Each unit spread over 3 weeks, comprises of

1. Theory - 48 hours with maximum of 3 hours daily
2. Practical - 72 hours with minimum of 4 hours daily
Total = 36 weeks (9 months approximately)
* Module 4 & Module 8 will require 15 days each (Total 1 Month)
Total Duration: 10 Months + Project
Programme Fee
The fees for the entire programme is Rs. 1,08,000.
Unique Features
• Unique programme in line with the current requirement of the IT industry
• State-of-the-art computer laboratory
• Interaction with industry professionals on technical & non-technical topics
• Practical hands-on sessions, extended lab sessions
• Industry visits to IT companies
• Educational loan assistance
• Excellent placement assistance
• Free-ships to meritorious and needy students

Opportunites
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.
ADSD's intensive programme structure is in-line with Industry needs and therefore, assures quality trained IT professionals ready to serve the industry.
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.
Having acquired sound knowledge and skill sets, ADSD graduates can easily accept IT industry challenges, allowing them to succeed in short span of time.

MET has a strong alumni base of over 4000 successful IT professionals worldwide with many of them at top positions in leading companies.
Programme Outline
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.
Right from the programming languages & 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.
Visit Following Site For More Information :
MET ISDR


Sunday, May 3, 2009

In-Depth look at the GridView Control

Introduction:
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.

Adding a SqlDataSource and binding to GridView Control:
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:

void Page_Load(object sender, EventArgs e)
{

if (!Page.IsPostBack)
{

// Binds the data

BindData();

}

}

public void BindData()
{

// you can use this line

string connectionString = myDataSource.ConnectionString;

// you can also use this line since by using the SqlDataSource it makes an entry in the
// web.config file if that is what choose to do
//string connectionString = (string)ConfigurationSettings.AppSettings["ConnectionString"];
// if you are using Enterprise Library you can also use
//string connectionString = (string)ConfigurationSettings.ConnectionStrings["ConnectionString"];

SqlConnection myConnection = new SqlConnection(connectionString);

SqlDataAdapter ad = new SqlDataAdapter("SELECT * FROM Categories", myConnection);

DataSet ds = new DataSet();

ad.Fill(ds, "Categories");

myGridView.DataSource = ds;

myGridView.DataBind();

}


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.



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:



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.

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.



Editing in the Grid View Control
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.

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.

Edit Mode:
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.

// Editing mode

void myGridView_RowEditing(object sender, GridViewEditEventArgs e)
{

myGridView.EditIndex = e.NewEditIndex;

BindData();

}

Cancel Edit:
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.

// Cancel Edit Mode

void myGridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{

myGridView.EditIndex = -1;

BindData();

}

Selecting Row:
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:

// Selecting row

void myGridView_SelectedIndexChanged(object sender, EventArgs e)
{

// This will contain the selectedValue of the row

string selectedCategory = myGridView.SelectedRow.Cells[1].Text;

}


The Cells start with index '0' which means Cell[0] is CategoryID , Cell[1] is CategoryName and so on.

Update Row:
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.

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.

void myGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{

GridViewRow row = myGridView.Rows[e.RowIndex];

if (row != null)

{

TextBox t = row.FindControl("TextBox1") as TextBox;

if (t != null)

{

Response.Write("The Text Entered is" + t.Text);

}

}

Paging:
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.

// Grid View Paging

void myGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{

myGridView.PageIndex = e.NewPageIndex;

BindData();

}

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.



Using SqlDataSource to execute commands:
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.

When you use SqlDataSource you gets the advantage of having the paging, sorting implemented automatically which is pretty cool in some cases.

In the next article we will see some more features of the Grid View control. I hope you liked the article

Happy Programming !

Encryption and Decryption Functions

Microsoft provides very good classes for encryption and decryption under the following namespace.
System.Security.Cryptography.
Coding Sample Given as follows:

using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using System.Security.Cryptography;

///
/// Class which contains static reusable methods for encrypting a string.
/// Mainly constructed for URL encryption but further can be used for string encryption
/// needed in other operation.
///

public class Cryptex
{
public Cryptex()
{
//
// TODO: Add constructor logic here
//
}

internal static HttpServerUtility sUtil = HttpContext.Current.Server;

///
/// Method used to encrypt a string making use of DES Algorithm.
///

///
///
///
public static string StringEncrypt_DES(string queryString) {

DESCryptoServiceProvider des = new DESCryptoServiceProvider();
string key = ConfigurationManager.AppSettings["DESCryptokey"];

des.Key = Encoding.UTF8.GetBytes(key.Substring(0, 8));
des.IV = Encoding.UTF8.GetBytes(key.Substring(0, 8));
ICryptoTransform cryptotransform = des.CreateEncryptor();
try {
MemoryStream mStream = new MemoryStream();
CryptoStream cryptostream = new CryptoStream(mStream, cryptotransform, CryptoStreamMode.Write);
StreamWriter writer = new StreamWriter(cryptostream);

writer.WriteLine(queryString);
writer.Close();
cryptostream.Close();

byte[] buffer = mStream.ToArray();
mStream.Close();
return Convert.ToBase64String(buffer);
}
catch {
throw;
}
return string.Empty;
}

///
/// Method used to dencrypt a string making use of DES Algorithm.
///

///
///
///
public static string StringDecrypt_DES(string queryString) {

DESCryptoServiceProvider des = new DESCryptoServiceProvider();
string key = ConfigurationManager.AppSettings["DESCryptokey"];

des.Key = Encoding.UTF8.GetBytes(key.Substring(0, 8));
des.IV = Encoding.UTF8.GetBytes(key.Substring(0, 8));
try {
queryString = sUtil.UrlDecode(queryString);

byte[] buffer = Convert.FromBase64String(queryString.Trim());

MemoryStream mStream = new MemoryStream(buffer);
ICryptoTransform cryptotransform = des.CreateDecryptor();
CryptoStream cryptostream = new CryptoStream(mStream, cryptotransform, CryptoStreamMode.Read);

StreamReader reader = new StreamReader(cryptostream);

queryString = reader.ReadLine();
reader.Close();
cryptostream.Close();
mStream.Close();
}
catch {
throw;
}
return queryString;
}

///
/// Method used to encrypt a string making use of RC2 Algorithm.
///

///
///
///
public static string StringEncrypt_RC2(string inputString, string key) {

RC2CryptoServiceProvider rc2 = new RC2CryptoServiceProvider();
rc2.Mode = CipherMode.CBC;

rc2.Key = ASCIIEncoding.ASCII.GetBytes(key);
rc2.IV = ASCIIEncoding.ASCII.GetBytes(key);
ICryptoTransform cryptotransform = rc2.CreateEncryptor();
return encrypt(inputString, cryptotransform);
}
///
/// Method used to dencrypt a string making use of RC2 Algorithm.
///

///
///
///
public static string StringDecrypt_RC2(string inputString, string key) {

RC2CryptoServiceProvider rc2 = new RC2CryptoServiceProvider();
rc2.Mode = CipherMode.CBC;

rc2.Key = ASCIIEncoding.ASCII.GetBytes(key);
rc2.IV = ASCIIEncoding.ASCII.GetBytes(key);
ICryptoTransform cryptotransform = rc2.CreateDecryptor();
return decrypt(inputString, cryptotransform);
}
///
/// Method used to encrypt a string making use of Rijndael Algorithm.
///

///
///
///
public static string StringEncrypt_RIJNDAEL(string inputString, string key) {

Rijndael rijndael = new RijndaelManaged();
rijndael.Mode = CipherMode.CBC;
rijndael.Key = ASCIIEncoding.ASCII.GetBytes(key);
rijndael.IV = ASCIIEncoding.ASCII.GetBytes(key);
ICryptoTransform cryptotransform = rijndael.CreateEncryptor();
return encrypt(inputString, cryptotransform);
}

///
/// Method used to dencrypt a string making use of Rijndael Algorithm.
///

///
///
///
public static string StringDecrypt_RIJNDAEL(string inputString, string key) {

Rijndael rijndael = new RijndaelManaged();
rijndael.Mode = CipherMode.CBC;
rijndael.Key = ASCIIEncoding.ASCII.GetBytes(key);
rijndael.IV = ASCIIEncoding.ASCII.GetBytes(key);
ICryptoTransform cryptotransform = rijndael.CreateDecryptor();
return decrypt(inputString, cryptotransform);
}

protected static string encrypt(string Str, ICryptoTransform cryptotransform) {
try {
MemoryStream mStream = new MemoryStream();
CryptoStream cryptostream = new CryptoStream(mStream, cryptotransform, CryptoStreamMode.Write);
StreamWriter writer = new StreamWriter(cryptostream);

writer.WriteLine(Str.Trim());
writer.Close();
cryptostream.Close();

byte[] buffer = mStream.ToArray();
mStream.Close();
Str = sUtil.UrlEncode(Convert.ToBase64String(buffer));
}
catch{
throw;
}
return Str;
}

protected static string decrypt(string Str, ICryptoTransform cryptotransform) {
try {
Str = sUtil.UrlDecode(Str.Trim());
byte[] buffer = Convert.FromBase64String(Str);

MemoryStream mStream = new MemoryStream(buffer);
CryptoStream cryptostream = new CryptoStream(mStream, cryptotransform, CryptoStreamMode.Read);
StreamReader reader = new StreamReader(cryptostream);
Str = reader.ReadLine();
reader.Close();
cryptostream.Close();
mStream.Close();
}
catch {
throw;
}
return Str;
}

const string DESKey = "AQWSEDRF";
const string DESIV = "AQWSEDRF";

public static string DESDecrypt(string stringToDecrypt)//Decrypt the content
{
byte[] key;
byte[] IV;

byte[] inputByteArray;
try {
key = Convert2ByteArray(DESKey);
IV = Convert2ByteArray(DESIV);
int len = stringToDecrypt.Length; inputByteArray = Convert.FromBase64String(stringToDecrypt);
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(key, IV), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
Encoding encoding = Encoding.UTF8; return encoding.GetString(ms.ToArray());
}
catch (System.Exception ex) {
throw ex;
}
}

public static string DESEncrypt(string stringToEncrypt)// Encrypt the content
{
byte[] key;
byte[] IV;

byte[] inputByteArray;
try {
key = Convert2ByteArray(DESKey);
IV = Convert2ByteArray(DESIV);
inputByteArray = Encoding.UTF8.GetBytes(stringToEncrypt);
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(key, IV), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
return Convert.ToBase64String(ms.ToArray());
}
catch (System.Exception ex) {
throw ex;
}
}

static byte[] Convert2ByteArray(string strInput) {

int intCounter; char[] arrChar;
arrChar = strInput.ToCharArray();
byte[] arrByte = new byte[arrChar.Length];
for (intCounter = 0; intCounter <= arrByte.Length - 1; intCounter++)
arrByte[intCounter] = Convert.ToByte(arrChar[intCounter]);
return arrByte;
}
}



For More Info Follow Following Link :

http://msdn.microsoft.com/en-us/library/system.security.cryptography.asnencodeddataenumerator.aspx