-->

Friday, March 14, 2014

LINQ Standard Query Operators in ASP.NET

The standard query operators are the methods that form the LINQ pattern. The standard query operators provide query capabilities including filtering, projection, aggregation, sorting, and much more. The standard query operator in LINQ is an Application Programming Interface (API) that enables querying of any .NET array or collection. You can use these standard query operators to operate on sequence.

The following are two set of standard query operators in LINQ:

1.  The first type is the one that operates on objects of the type IEnumerable<T>.
2.  The second one is the one that operates on object of the type IQueryable<T>.

The standard query operators differ in the time that they take for their execution. The time depends on whether they have to return a single value or a sequence of values. The methods that return a single value execute immediately. The methods that return a sequence of values reschedule the query execution and return an enumerable object.

List of all Query operators are:

Filtering Operator: Restricts the result set to contain those elements that satisfy a specific condition that are
returned
Projection Operator: Transforms an object into a different type of new object
Sorting Operator:  Changes the order of elements of sequence returned by the query
Join Operator: Combines collections
Grouping Operator: Puts the data into groups
Quantifier Operator: Checks whether an element of a sequence satisfies a condition
Partitioning Operator: Returns a subset of collection
Set Operator:  Returns a result set which is in the form of a collection
Element Operator:  Returns just one element
Aggregate Operator:  Computes a single value from a collection
Conversion Operator: Converts the collection to an array
Generation Operator: Returns a new sequence of values

Introducing LINQ Queries in ASP.NET

Language Integrated Query (LINQ) is a new component of .NET Framework. The basic function of LINQ is to add native data querying capabilities to .NET Framework by using syntax similar to Structured Query Language (SQL). LINQ allows you to define statements that query a data source to generate the requested result set.
LINQ is an attempt to provide a consistent method to obtain and manipulate data. You can use LINQ directly within the ASP.NET programming language entities called query expressions. These query expressions are based on numerous query operators that have been designed to work in a manner similar to that of SQL. LINQ defines the set of query operators, which are used to query and filter the data. The difference between LINQ and SQL is that that unlike SQL, the query expressions in LINQ can be used to interact with numerous types of data, even the data that does not belong to a relational database.

A query is an expression that retrieves the requested data from a data source. A LINQ query specifies the information that you want to retrieve from a data source. LINQ queries can also perform additional functions, such as sorting and grouping the retrieved data . The LINQ queries are written in declarative query syntax. The various clauses that you can use with the LINQ query are the From, Where, OrderBy, and Select clauses. They are the predefined clauses that you can use for the execution of a LINQ query.
The basic syntax of using a LINQ query is that the LINQ query expressions must start with the From clause and end with the Select or the Group clause. You can use the Where and OrderBy clauses to perform additional functions such as retrieving the data.

The following are three basic steps of a LINQ query execution:

1.  The first step in the LINQ query execution is to obtain the data source. The data source can be either a SQL database or an XML file.
2.  The second step is to create the query.
3.  Lastly, you need to execute your LINQ query.

Before you work with LINQ queries, you need to be aware of the following basic concepts:

□ Data Sources in LINQ Queries
□ Deferred Query Execution and Immediate Execution
□ LINQ and Generic Types

Data Sources in LINQ Queries

The data source in a LINQ query can be a data structure, a Web service, a file system, or a database. LINQ query execution is simple because the syntax and the pattern of the query do not change with the change in the data source. The different ways in which you can use LINQ with different data sources are as follows:
□ You should implement the IEnumerable<T> interface for enabling the LINQ to Objects querying.
□ You can create standard query operator methods, such as Where and Select, to enable custom LINQ queries
□ You can also create a provider for your data source that implements the IQueryable<T> interface to enable LINQ queries. A provider that implements this interface receives LINQ queries in the form of expression trees.
□ You can also create a provider that enables not only querying but also insert, update, and delete operations.

When you retrieve data using LINQ, the data source is not important. Execution of LINQ queries are independent of data types of data and structure of original data source.
LINQ previews the data source as an IEnumerable<T> or IQueryable<T> collection. For example, in LINQ to SQL, the source data is made visible as an IEnumerable<XElement> collections element. In LINQ to DataSet, the source data is made visible as an IEnumerabie<DataRow> collections."

Deferred Query Execution and Immediate Execution

The LINQ query only stores query commands. When vou define a query in LINQ during runtime, the query does not run. The query runs when the items are iterated. The query variable only stores the query commands. The actual execution of LINQ query is held back until you iterate over the query variable in a ForEach statement. This concept of holding back the actual execution is termed as deferred query execution. You can use the ForEach statement to retrieve the LINQ query results. For example, in a database that is updated continuously, you can create a LINQ query that retrieves the latest data, and you can also execute it repeatedly at different intervals to retrieve different results every time.

If the queries perform aggregation functions over a range, the elements must first iterate over the range. Ihis is called immediate execution. These functions must first iterate over the source elements and then display the result. The clauses that perform such kind of forced execution are Count, Max, Min, and Average. Unlike deferred execution, immediate execution of queries does not require an explicit ForEach statement to return the result.

If you compare deferred to immediate query execution, deferred query execution has an edge over the immediate query execution. This is because in deferred query execution the query does not hold the result. You can execute it as often as you like. You can also update the data source on a regular basis by a separate application. You can retrieve the latest data in deferred query execution. This kind of functioning is not possible in immediate query execution.

LINQ and Generic Types

The LINQ queries are based on generic types. These types were introduced with .NET Framework 2.0. The generic types are used to maximize code reuse, type safety, and performance. The most common use of generic is to create collection classes. There are two basic concepts of the generic types used in LINQ:
1.  In a LINQ query, when you create an instance of a generic collection class, such as List<T>, you replace the T with the type of objects that the list will hold. For example, a list of strings is represented as List<String> and a list of Customer object is represented as List<Customer>. A generic list provides many benefits over collections that store their elements as Objects. For example, if you try to add a Customer to a List<String>, you will get a compile-time error. In such cases, it is easy to use generic collections as you do not need to perform run-time type-casting.
2.  The second generic type that LINQ uses is the IEnumerable<T> interface. It enables the generic collection classes to be enumerated by using the ForEach loop. For example, a LINQ query variable that is typed as IEnumerable<Customer> means that when the query is executed it will produce a sequence of zero or more Customer objects.

GridView Header's Border style change in ASP.NET

Initial Steps for viewers

Step-1 : Open Visual Studio IDE
Step-2 : Add New Webform into your project
Step-3 : Open Design page for adding control onit.
Step-4 : You can change it from Property bar
GridView Header's Border style change in ASP.NET



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

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:GridView ID="GridView1" runat="server" AllowPaging="True"
        AutoGenerateColumns="False" DataKeyNames="Sno" DataSourceID="SqlDataSource1">
        <Columns>
            <asp:BoundField DataField="Sno" HeaderText="Sno" InsertVisible="False"
                ReadOnly="True" SortExpression="Sno" />
            <asp:BoundField DataField="name" HeaderText="name" SortExpression="name" />
            <asp:BoundField DataField="address" HeaderText="address"
                SortExpression="address" />
            <asp:BoundField DataField="contactno" HeaderText="contactno"
                SortExpression="contactno" />
        </Columns>

 <HeaderStyle BorderStyle="Ridge" />

    </asp:GridView>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server"
        ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
        DeleteCommand="DELETE FROM [userdataTable] WHERE [Sno] = @Sno"
        InsertCommand="INSERT INTO [userdataTable] ([name], [address], [contactno]) VALUES (@name, @address, @contactno)"
        SelectCommand="SELECT * FROM [userdataTable]"
        UpdateCommand="UPDATE [userdataTable] SET [name] = @name, [address] = @address, [contactno] = @contactno WHERE [Sno] = @Sno">
        <DeleteParameters>
            <asp:Parameter Name="Sno" Type="Int32" />
        </DeleteParameters>
        <InsertParameters>
            <asp:Parameter Name="name" Type="String" />
            <asp:Parameter Name="address" Type="String" />
            <asp:Parameter Name="contactno" Type="Int32" />
        </InsertParameters>
        <UpdateParameters>
            <asp:Parameter Name="name" Type="String" />
            <asp:Parameter Name="address" Type="String" />
            <asp:Parameter Name="contactno" Type="Int32" />
            <asp:Parameter Name="Sno" Type="Int32" />
        </UpdateParameters>
    </asp:SqlDataSource>
    <div>
   
    </div>
    </form>
</body>
</html>

Code Generate the following output:

GridView Header's Border style change in ASP.NET

Example of Top Text alignment of Gridview in asp.net

Initial Steps for viewers

Step-1 : Open Visual Studio IDE
Step-2 : Add New Webform into your project
Step-3 : Open Design page for adding control onit.
Step-4 : You can change GridView Text alignment using Property bar.

Example of Top Text alignment of Gridview in asp.net


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

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

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:GridView ID="GridView1" runat="server" AllowPaging="True" 
        AutoGenerateColumns="False" DataKeyNames="Sno" DataSourceID="SqlDataSource1">
        <Columns>
            <asp:BoundField DataField="Sno" HeaderText="Sno" InsertVisible="False" 
                ReadOnly="True" SortExpression="Sno" />
            <asp:BoundField DataField="name" HeaderText="name" SortExpression="name" />
            <asp:BoundField DataField="address" HeaderText="address" 
                SortExpression="address" />
            <asp:BoundField DataField="contactno" HeaderText="contactno" 
                SortExpression="contactno" />
        </Columns>

 <HeaderStyle VerticalAlign="Top" />

    </asp:GridView>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
        ConnectionString="<%$ ConnectionStrings:ConnectionString %>" 
        DeleteCommand="DELETE FROM [userdataTable] WHERE [Sno] = @Sno" 
        InsertCommand="INSERT INTO [userdataTable] ([name], [address], [contactno]) VALUES (@name, @address, @contactno)" 
        SelectCommand="SELECT * FROM [userdataTable]" 
        UpdateCommand="UPDATE [userdataTable] SET [name] = @name, [address] = @address, [contactno] = @contactno WHERE [Sno] = @Sno">
        <DeleteParameters>
            <asp:Parameter Name="Sno" Type="Int32" />
        </DeleteParameters>
        <InsertParameters>
            <asp:Parameter Name="name" Type="String" />
            <asp:Parameter Name="address" Type="String" />
            <asp:Parameter Name="contactno" Type="Int32" />
        </InsertParameters>
        <UpdateParameters>
            <asp:Parameter Name="name" Type="String" />
            <asp:Parameter Name="address" Type="String" />
            <asp:Parameter Name="contactno" Type="Int32" />
            <asp:Parameter Name="Sno" Type="Int32" />
        </UpdateParameters>
    </asp:SqlDataSource>
    <div>
    
    </div>
    </form>
</body>
</html>

Code Generate the Following output

Example of Top Text alignment of Gridview in asp.net

GridView Row background color in ASP.NET

Initial Steps for viewers

Step-1 : Open Visual Studio IDE
Step-2 : Add New Webform into your project
Step-3 : Open Design page for adding control onit.
Step-4 : You can change Background color from property menu.
GridView Row background color in ASP.NET

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

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

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:GridView ID="GridView1" runat="server" AllowPaging="True" 
        AutoGenerateColumns="False" DataKeyNames="Sno" DataSourceID="SqlDataSource1">
        <Columns>
            <asp:BoundField DataField="Sno" HeaderText="Sno" InsertVisible="False" 
                ReadOnly="True" SortExpression="Sno" />
            <asp:BoundField DataField="name" HeaderText="name" SortExpression="name" />
            <asp:BoundField DataField="address" HeaderText="address" 
                SortExpression="address" />
            <asp:BoundField DataField="contactno" HeaderText="contactno" 
                SortExpression="contactno" />
        </Columns>

 <RowStyle BackColor="#FF3399" />

    </asp:GridView>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
        ConnectionString="<%$ ConnectionStrings:ConnectionString %>" 
        DeleteCommand="DELETE FROM [userdataTable] WHERE [Sno] = @Sno" 
        InsertCommand="INSERT INTO [userdataTable] ([name], [address], [contactno]) VALUES (@name, @address, @contactno)" 
        SelectCommand="SELECT * FROM [userdataTable]" 
        UpdateCommand="UPDATE [userdataTable] SET [name] = @name, [address] = @address, [contactno] = @contactno WHERE [Sno] = @Sno">
        <DeleteParameters>
            <asp:Parameter Name="Sno" Type="Int32" />
        </DeleteParameters>
        <InsertParameters>
            <asp:Parameter Name="name" Type="String" />
            <asp:Parameter Name="address" Type="String" />
            <asp:Parameter Name="contactno" Type="Int32" />
        </InsertParameters>
        <UpdateParameters>
            <asp:Parameter Name="name" Type="String" />
            <asp:Parameter Name="address" Type="String" />
            <asp:Parameter Name="contactno" Type="Int32" />
            <asp:Parameter Name="Sno" Type="Int32" />
        </UpdateParameters>
    </asp:SqlDataSource>
    <div>
    
    </div>
    </form>
</body>
</html>

Code generate the following output

GridView Row background color in ASP.NET

Thursday, March 13, 2014

GridView Row border color in ASP.NET

Initial Steps for viewers

Step-1 : Open Visual Studio IDE
Step-2 : Add New Webform into your project
Step-3 : Open Design page for adding control onit.
Step-4 : You can change Border color from property menu.
GridView Row border color in ASP.NET

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

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

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:GridView ID="GridView1" runat="server" AllowPaging="True" 
        AutoGenerateColumns="False" DataKeyNames="Sno" DataSourceID="SqlDataSource1">
        <Columns>
            <asp:BoundField DataField="Sno" HeaderText="Sno" InsertVisible="False" 
                ReadOnly="True" SortExpression="Sno" />
            <asp:BoundField DataField="name" HeaderText="name" SortExpression="name" />
            <asp:BoundField DataField="address" HeaderText="address" 
                SortExpression="address" />
            <asp:BoundField DataField="contactno" HeaderText="contactno" 
                SortExpression="contactno" />
        </Columns>

 <RowStyle BorderColor="Red" />

    </asp:GridView>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
        ConnectionString="<%$ ConnectionStrings:ConnectionString %>" 
        DeleteCommand="DELETE FROM [userdataTable] WHERE [Sno] = @Sno" 
        InsertCommand="INSERT INTO [userdataTable] ([name], [address], [contactno]) VALUES (@name, @address, @contactno)" 
        SelectCommand="SELECT * FROM [userdataTable]" 
        UpdateCommand="UPDATE [userdataTable] SET [name] = @name, [address] = @address, [contactno] = @contactno WHERE [Sno] = @Sno">
        <DeleteParameters>
            <asp:Parameter Name="Sno" Type="Int32" />
        </DeleteParameters>
        <InsertParameters>
            <asp:Parameter Name="name" Type="String" />
            <asp:Parameter Name="address" Type="String" />
            <asp:Parameter Name="contactno" Type="Int32" />
        </InsertParameters>
        <UpdateParameters>
            <asp:Parameter Name="name" Type="String" />
            <asp:Parameter Name="address" Type="String" />
            <asp:Parameter Name="contactno" Type="Int32" />
            <asp:Parameter Name="Sno" Type="Int32" />
        </UpdateParameters>
    </asp:SqlDataSource>
    <div>
    
    </div>
    </form>
</body>
</html>

Code generate the following output

How to use Default Constraint on Column in SQL

A default constraint can be used to assign a constant value to a column, and the user need not insert value for such a column. Only one default constraint can be created for a column but the column cannot be an identity column. The system-supplied values, such as USER, CURRENT_USER, and user-defined values can be assigned as defaults.

The syntax of applying the default constraint while creating a table is:

CREATE TABLE table_name
(
Col_name [CONSTRAINT constraint_name] DEFAULT (constant_expression|NULL)
(col_name [, col_name [, …]])
.
)
Where,

  • Constraint_name specifies the name of the constraint to be created.
  • Constant_expression specifies an expression that contains only constant values. This can contain a NULL value.

In the example of creating the EmployeeLeave table, you can insert a default constraint to add a default value for the LeaveType column. You can set the default leave type as PL. You can use the following statement to create the default constraint:

CREATE TABLE HumanResources.EmployeeLeave
(
EmployeeID int CONSTRAINT fkEmployeeID FOREIGN KEY REFERENCES Humanresources.Employe (EmployeeID),
LeaveStartDate datetime CONSTRAINT cpkLeaveStartDate PRIMARY LeaveEndDate datetime NOT NULL,
LeaveReason varchar(100),
LeaveType char(2) CONSTRAINT chkLeave CHECK (LeaveType IN (‘ CL’, ‘SL’, ‘PL’)) CONSTRAINT chkDefLeave DEFAULT ‘PL’)

The preceding command creates the EmployeeLeave table with a default constraint on the LeaveType column, where the default value is specified as PL. The name of the constraint is chkDefLeave.

Check on Constraints
© Copyright 2013 Computer Programming | All Right Reserved