c#.net_unit_3_4_5

 

                               (Unit-III) Working with ADO.net

Introduction:

Microsoft ActiveX Data Objects.NET (ADO.NET) is a model used by .NET applications using which you can communicate with the database directly for retrieving and manipulating data.

 ADO.NET is the main data access system that .NET application uses. ADO.NET uses a disconnected data architecture, which means that the data you work with is just a copy of the data in the database.

New Features in ADO.NET

The new features of ADO.NET are as follows:

Ø  Language-Integrated Query (LINQ): LINQ is a new innovation and one of the components of .NET Framework 3.5 that adds native data capabilities to .NET languages using syntax similar to SQL. LINQ to ADO.NET is a LINQ technology to enable querying in ADO.NET using LINQ programming model. LINQ to ADO.NET consists of two related technologies: LINQ to DataSet and LINQ to SQL. LINQ to DataSet provides faster querying of data on the contents of a DataSet. LINQ to SQL enables you to directly query SQL Server databases.

Ø  LINQ to DataSet: LINQ to DataSet provides LINQ capabilities for disconnected data stored in dataset. LINQ to DataSet makes it easier and faster to query over data cached in a DataSet object. The LINQ to DataSet feature enables you to work more productively.

Ø  LINQ to SQL: LINQ to SQL is a component of .NET 3.5 Framework that provides a run-time infrastructure for managing relational data as objects. You can use LINQ to SQL technology for translating a query into a SQL query, and then issue it against tables in a SQL Server database. LINQ to SQL supports all the key capabilities that you would expect while working with SQL. You can inset, update, and delete the information from the table.

Explain Components of ADO.Net

ADO.NET contains a set of classes that expose data access services. It provides a rich set of components for creating distributed applications. ADO.NET uses a logical process flow containing components.

 

The two main components of ADO.NET for accessing and manipulating data are data provider and dataset. The data provider contains the Connection, Command, DataReader, and DataAdapter objects. The connection object provides connectivity to the database. The Command object provides access to database commands for retrieving and manipulating data in a database. The DataReader  object retrieves data from the database in a read-only, forward-only mode. The DataAdapter object uses Command objects to execute SQL commands. The DataAdapter  loads  the DataSet object with data and also resolves changes that were made to the data in the DataSet object back to the database.

Data Providers 

The data provider contains the following four main objects:

Ø  Connection: Establishes connection with the database. The base class for all the Connection objects is the DbConnection class. The Connection objects have the methods for opening and closing connection. The .NET framework provides two types of Connection objects: the SqlConnection object, which is designed specifically to connect to Microsoft SQL Server and the OleDbConnetion object, which is designed to provide connections to a wide range of databases, such as Microsoft Access and Oracle.

Ø  Command: Executes a command against the database and retrieves a DataReader or DataSet. It also executes the INSERT, UPDATE, or DELETE command against the database. The base class for all Command objects is the DbCommand class. The Command object is represented by two classes: SqlCommand and OleDbCommand. The Command object provides three methods that are used to execute commands on the database. The ExecuteNonQuery() method executes the commands that have no return value such as INSERT, UPDATE, or DELETE. The ExecuteScalar() method returns a single value from a database query. The ExecuteReader() method returns a result set by way of the DataReader objet

Ø  DataReader: Retrieves data from the database in a forward-only, read-only mode. The base class for all DataReader objects is the DbDataReader class. The DataReader  object is returned as a result of calling the ExecuteReader() method of the Command object.

Ø  DataAdapter: retrieves data from the database and stores data in a dataset and reflects the changes made in the dataset to the database. The base class for all DataAdapter objects is the DbDataAdapter class. The DataAdapter object acts as intermediary for all the communication between the database and DataSet object. The DataAdapter object is used to fill a DataTable or DataSet objects with data from the database using the Fill() method. The DataAdapter object commits the changes to the database by calling the Update() method.

Datasets

The other major component of ADO.NET is the DataSet object. The DataSet object always remains disconnected from the database. Consequently reducing load on the database. The DataAdapter object is used to connect a dataset to a data provider. The DataAdapter object is used as an intermediary between the dataset and the data provider.

Q.Explain Basic Operations in ADO.NET

BASIC OPERATIONS IN ADO.NET

·         Creating a Connection to a Database

·         Executing Commands by using Command object

·         Adding and Configuring a Data Adapter

·         Creating a Data Set

·         Using Data Adapter to retrieve data in a Data Set

v  Creating a Connection to a Database

For working with the data from a database, you need to first establish a connection with the database.

Using the Wizard

You can create a connection string for any data provider using the wizard. Here you can see a simple example to connect to the Northwind database.

1.       Open Microsoft Visual Studio 2008 from Startà All Programsà Microsoft Visual Studio 2008à Microsoft Visual Studio 2008.

2.       Select Fileà New à Project. The New Project dialog box appears.

3.       In the New Project dialog box, select Visual C# under the Project types pane and Windows Forms Application from the Templates pane.

4.       Enter the name for the application as DatabaseOperationsExample and also provide a location for the application.

5.       Click the OK button to create a DatabaseOperationsExample application.

6.       Select Viewà Server Explorer to open the Server Explorer window.

7.       Right-click the Data Connections option from the Server Explorer window and select the Add Connection option from the context menu.

 The Add Connection dialog box appears from where you can select the type of data source you    want to attach to your application.

8.       Click the Change button to select the data source for your application. The Change Data Source dialog box appears from where you can select the data source.

9.       Select Microsoft SQL Server as the data source to connect to a SQL Server database.

10.   Click the OK button. The Add Connection dialog box reappears with the Microsoft SQL Server (SqlClient) option selected as a data source.

11.   Select the server name from the Server name drop-down list.

        By default, the radio button beside the Use Windows Authentication option is selected. If    you want to use SQL Server authentication, then click the radio button beside the Use SQL Server Authentication option, and provide user name and password for authentication.

12.   Now, select the database or enter the name of the database you want to connect to in the Select or enter a database name drop-down list.

13.    Click the Test Connection button. A message box appears with the message Test Connection succeeded.

14.    Click the OK button of the message box.

15.    Now, click the OK button of the Add Connection dialog box. You will notice tht the data source is added to your application in the Server Explorer.

Using a Connection String

  Use the ConnectionString property of the OleDbConnection class, for SQL Server, use the ConnectionString property of the SqlConnection class, and for an Oracle data source, use the ConnectionString property of the OracleConnection class.

In the SQL Server connection string, the parameters are discussed as follows:

Ø  Data Source: Represents the name or the network address of the SQL Server instance to which you need to connect.

Ø  Initial Catalog: Represents the name of the database.

Ø  Integrated Security: Accepts two Boolean values either True or False. If the value is True then the current Windows account credentials are used for authentication. The default value is True.

Next, let’s see how to execute commands by using the Command object.

v  Using a Command Object  

The command object is one of the basic components of ADO .NET.

  1. The Command Object uses the connection object to execute SQL queries.
  2. The queries can be in the Form of Inline text, Stored Procedures or direct Table access.
  3. An important feature of Command object is that it can be used to execute queries and Stored Procedures with Parameters.
  4. If a select query is issued, the result set it returns is usually stored in either a DataSet or a DataReader object.

Now, Let us have a look at various Execute Methods that can be called from a Command Object.

 

Property

Description

ExecuteNonQuery

This method executes the command specifies and returns the number of rows affected.

ExecuteReader

The ExecuteReader method executes the command specified and returns an instance of SqlDataReader class.

ExecuteScalar

This method executes the command specified and returns the first column of first row of the result set. The remaining rows and column are ignored.

EX:

ExecuteNonQuery

1.    The ExecuteNonQuery method is used to execute the command and return the number of rows affected.

2.    The ExecuteNonQuery method cannot be used to return the result set.

 string connectionString = @"server=localhost;userid=user1;password=12345;database=mydb";

 

MySqlConnection connection = null;

try

{

    connection = new MySqlConnection(connectionString);

    connection.Open();

    MySqlCommand cmd = new MySqlCommand();

    cmd.Connection = connection;

    cmd.CommandText = "INSERT INTO Customers(Name) VALUES(@Name)";

    cmd.Prepare();

 

    cmd.Parameters.AddWithValue("@Name", "Bill Gates");

    cmd.ExecuteNonQuery();   

}

finally

{

    if (connection != null)

        connection.Close();

}

 

v  Adding and Configuring a Data Adapter

1.       A data adapter enables you to access data from a database in a disconnected way. Let’s now learn how we can access data in a data adapter from a database by performing the following steps:

In the DatabaseOperationsExample application, set the Text property to Form1 to Basic Database Operations.

2.       Right-click the Data tab of the Toolbox and select the Choose Items option from the context menu that appears.

          The choose Toolbox Items dialog box appears.

3.       Under the .NET Framework Components tab in the Choose Toolbox Items dialog box, click the check box beside the SqlDataAdapter option.

4.       Then click the OK button to close the Choose Toolbox Items dialog box. The Choose Toolbox Items dialog box closes and the SqlDataAdapter control is added to the Toolbox.

5.       Now, drag and drop a SqlDataAdapter control to the form. The Data Adapter Configuration Wizard appears.

6.       Select the existing connection from the Which data connection should the data adapter use? Drop-down list or create a new connection by clicking the New Connection button. Clicking the New Connection button opens the Add Connection dialog box.

7.       Click the Next button. The next page appears for Data Adapter Configuration Wizard, which prompts the user to select a command type.

  The page displays the following three options to select:

Ø  Use SQL statements: select this option to allow the data adapter use a SQL statement to populate a table in a dataset. This option is by default selected.

Ø  Create new stored procedures: Select this option to create a new stored procedure to read and update a table from the database.

Ø  Use existing stored procedures: Select this option to allow the data adapter to use an existing stored to read and update a table from the database.

     In this case, we will go with the first option that is the  Use SQL statements option.

8.       Click the Next button. The next page appears for the Data Adapter Configuration Wizard which prompts the user to generate an SQL statement.

9.       Now, either create a SQL statement or select the existing stored procedures. For building a SQL statement, click the Query Builder button. The Query Builder dialog box appears along with a Add Table dialog box.

10.   Select the table, for example Employees from the Add Table dialog box.

11.    Click the Add button to add the Employees table to the Query Builder.

12.   Now click the close button to close the Add Table. The Employees table is added to the Query Builder dialog box.

  At the top of the Query Builder dialog box, you can see all the fields of the Employees table either you can select some fields or all the fields from the table.

13.   Select the check box beside the *(All Columns) option from the Employees table.

14.   Click the OK button to create the SQL statement. You can see that the SQL statement appears in the Data Adapter Configuration Wizard.

15.   Click the Next button. Data Adapter Configuration Wizard appears with the information of successful configuration of the data adapter.

16.   Click the Finish button to close the Data Adapter Configuration Wizard. You can see a data adapter, sqlDataAdapter1 and a connection object, sqlConnection1  appears on the Component Tray.

17.   Now select Dataà Preview Data to preview the data from the data adapter.

The Preview Data dialog box appears.

18.   Click the Preview button to view the data from the database in the Results pane.

19.   Finally, click the close button to close the Preview Data dialog box.

 

v  Creating a Dataset

           Datasets as already explained, contains a cached copy of the tables of as database. The dataset is independent of the database and so the interaction with existing databases is controlled through the data adapter. You can fill data in a dataset by using the Fill() method of the data adapter.

Now, let’s create a dataset by performing the following steps:

1.       Open the DatabaseOpearationsExample application

2.       Select Dataà Generate Dataset.

The Generate dataset dialog box appears, which prompts the user to select a dataset.

You can select an existing dataset or create a new one. By default, the new radio button is selected. You can provide a name for the new dataset or you can use the existing default name as DataSet1. The generate Dataset dialog box also prompts the user to select a table to add to the dataset. By default the table Employees is selected.

3.       Now, click the Ok button to add the dataset to the application. The dataset, dataset11, is added to the Component Tray.

Using a Data Adapter to Retrieve Data in a Dataset

 So far, we have created a data adapter and a dataset. Let’s now see how to display data on a DataGridView  control using data adapter and dataset. To do so, perform the following steps:

1.       Open the DatabaseOperationsExample application.

2.       Drag and drop a DataGridView control from the Data tab of the Toolbox to the form. A smart tag appears.

3.       Select a data source, for example, DataSet1 from the Choose Data Source drop-down list.

The dataSet11BindingSource binding source is added to the Component Tray.

4.       Now, again select the Choose Data Source drop-down list and select the Employees table.

The employeesBindingSource binding source is added to the Component Tray.

5.       Resize the form to accommodate the data of the Employees table.

6.       Import the System.Data.SqlClient namespace by using the using statement as shown in the following code snippet:

      Using System.Data.SqlClient;

7.       Add the code snippet as listed in the Load event of the form to display employee details on a DataGridView control.

    Private void Form1_Load(object sender, EventArgs e)

            {

                sqlDataAdapter1.Fill(dataset11);

             }

The Fill() method is used to populate the dataset dataSett11 with employees details.

8.       Press the F5 key to execute the DatabaseOperationsExample application.

Explain the types of Data Binding in Windows Forms

 Data binding means to bind controls to display data sources. Data binding can be used to bind either a particular field in a table or bind the entire table to a control.

There are two types of data binding in Windows forms:

·         Simple data binding

·         Complex data binding.

Simple Data Binding

Simple data binding allows you to display one data element, such as a field’s value from a table on a control in Visual Basic, you can simple bind any property of a control to a data value.

For example, you can bind a Text property of a TextBox control, Size and image properties of a PictureBox control or the BackColor property of a Label control to a data source. You can bind a property of a control to a data source by using the DataBindings property of the control.

In simple terms, you can say that simple data binding is the ability of a control to bind a single data element.

Let’s see an example of simple data binding. For that, perform the following steps:

1.       Create an application named WindowsFormsDataBinding.

2.       Set the Text property of Form1 to Simple Data Binding.

3.       Drag and drop the controls n Form1 and also set the values for the respective properties of the controls.

4.       Import the System.data.SqlClient namespace by using the using statement.

                using  System.Data.SqlClient;

5.       Now add the code in the Load event of Form1 to display the details of the employee whose EmployeeID is 6:

private void Form1_Load(object sender, EventArgs e)  

{

SqlConnection con;

con = new SqlConnection(“Data Source=SUMITA-PC\\SQLEXPRESS;Initial

Catalog=northwnd; Integrated Security=True”);

con.Open();

DataSet ds= new DataSet();

SqlDataAdapter da = new SqlDataAdapter(“Select * from Employees where Employee=6”, con);

da.Fill(ds, “Employees”);

textBox1.DataBindings.Add(“Text”, ds, “Employees.EmployeeId”);

textBox2.DataBindings.Add(“Text”, ds, “Employees.LastName”);

textBox3.DataBindings.Add(“Text”, ds, “Employees.FirstName”);

textBox4.DataBindings.Add(“Text”, ds, “Employees.Title”);

}

6.       Press the F5 key to execute the WindowsFormsDataBinding application .

Complex Data Binding

  Complex data binding enables binding of a control o more than one data element, such as more than one record in a database. Some of the controls that support complex data binding are DataGridView, ComboBox, ListBox, and CheckedListBox controls. Complex data binding can be performed using the following properties:

Ø  DataSource: Represents the data source, typically a dataset, such as dataSet11.

Ø  DataMember: Represents the data member you want to work with, in the data source, typically a table in a dataset, such as the Customers table in the NorthWind database. DataGridView control uses this property to determine which table to display.

Ø  DisplayMember: Represents the field you want a control to display, such as the customer’s id, CustomerID. ListBox control uses the DisplayMember and ValueMember properties instead of a DataMember property for data binding.

Ø  ValueMember: Represents the field you want the control to return in properties, such as returning the customer ID by using the SelectedValue property. The ListBox control uses the DisplayMember and ValueMember properties, instead of a DataMember property.

let’s see an example of complex data binding through code. For that, perform the following steps:

1.       Open the application named WindowsFormsDataBinding.

2.       Right-click the WindowsFormsDataBinding application in the Solution Explorer and select Add à Windows Forms from the context menu to add a new form to the application.

The Add New Item dialog box appears.

3.       Click the Add button to add Form2 to the application.

4.       Set the Text property to Form2 to Complex Data Binding.

5.       Resize the form to accommodate all employee details.

6.       Drag and drop a DataGridView control from the Data tab of the Toolbox to the form.

7.       Import the System.Data.SqlClient namespace by using the using statement.

                    using  System.Data.SqlClient;

8.       Now add the code in the Load event of Form2 to display the details of all employees in a data grid view:

  private void Form2_Load(object sender, EventArgs e) 

{

SqlConnection con;

con = new SqlConnection(“Data Source=SUMITA-PC\\SQLEXPRESS;Initial

Catalog=northwnd; Integrated Security=True”);

con.Open();

DataSet ds= new DataSet();

SqlDataAdapter da = new SqlDataAdapter(“Select * from Employees”, con);

da.Fill(ds, “Employees”);

dataGridView1.DataSource=ds;

dataGridView1.Datamember=”Employees”;

}

The DataSource property is used to bind a DataGridView control with the data source and the  DataMember property  is used to set the table name from which the employee details need to   be displayed.

9.       Set the start up form to Form2.

10.   Press the F5 key to execute the WindowsFormsDataBinding application.

 

UNIT –IV

What is LINQ?

LINQ (Language Integrated Query) is uniform query syntax in C# and VB.NET to retrieve data from different sources and formats.

For example, SQL is a Structured Query Language used to save and retrieve data from a database. In the same way, LINQ is a structured query syntax built in C# and VB.NET to retrieve data from different types of data sources such as collections, ADO.Net DataSet, XML Docs, web service and MS SQL Server and other databases.

C# LINQ usage

 

  Q. Explain Executing Simple LINQ Query.

·         A simple LINQ query is executed in a foreach statement.

·         The foreach statement in c# requires the IEnumerable or IEnumerable<T> interface.

·         A linq query contains three clauses: from ,where and select

Perform the following steps:

1.       Click start->all programs->Microsoft visual studio 2008-> to open the visual studio 2008 IDE

2.       In the Visual Studio 2008 IDE, select File->new-> project

3.       In the new project dialog box, select visual c#->windows in the project types pane and the windows form application option in the template pane

4.       Enter LinqQUERY in the name text box to specify the name of the application, and enter an appropriate location for the application in the location box.

5.       Click the ok button .linqQUERY application is created.

6.       Add a listview control and a button control to Form1 and change the Text property of button1 to Click.

7.       double click on button ,and add the code

 

int[] numbers=new int[7]{0,1,2,3,4,5,6};

var numquery=from num in numbers where (num%2)==0

select num;

foreach(int num in numquery)

{

Listview1.Items.Add(num.Tostring());

}

8.       press the F5 key to run the application

Q. Standard query operators in LINQ:

Operator Type

Description

Sorting

Changing the order of a sequence returned by a query

Set

Returns a result set in the form of a collection based on the presence or absence of elements

Filtering

Restricts the result set to contain the elements that satisfy a specific condition

Projection

Transforms an object into different type of new object

Partition

Divides the input sequence into two sections, without rearranging the elements and returns one section

Grouping

Puts the data into groups such that elements in each group share a common attribute.

Join

Joins two data sources with objects that share a common attribute in both the data sources.

Aggregate

Computes a single value from a collection

Zip

Combines two collections into one.

Sorting Operators

Sorting operators in LINQ arrange the elements of a sequence based on one or more attributes, it means that to use the sorting operator you first need to specify a particular attribute and perform primary sorting on the elements. The sorting operators are

Clauses

Description

OrderBy

Sorts a set of elements in ascending order

OrderByDescending

Sorts a set of elements in descending order

ThenBy

Perform a secondary sort on a set of elements, in ascending order

ThenByDescending

Performs a secondary sort on a set of elements, in descending order.

Set Operators:

Set operators in LINQ refers to the operators that are used to produce result set based on the presence or absence of the equivalent elements within the same or separate collection.

Set operators are

Operator

Description

Distinct

Removes duplicate values from a collection

Except

Removes elements from a collection that are not common to another collection

Intersect

Retrieves common elements from two collections.

Filter Operators:

Filter operators refer to an operation that modifies a result set according to the specified condition in such a manner that it contains only those elements that satisfy a specified condition. The filter operators are.

Operator

Description

OfType

Selects those values from a set of values that can be converted to a specified type

Where

Selects those values from a set of values that satisfy a given condition.

Projection Operators:

Projection operators refer to the operator that transform an object into new form; The new form generally consists of properties that will be used subsequently. The new form into which the objects are transformed is of a new type. The projection operators are

Operator

Description

Select

Projects(selects) values from a single sequence or collection

SelectMany

Projects(selects) values from multiple sequence or collections

 

 

Q.EXPLAIN SORTING OPERATORS IN LINQ

Sorting Operators in LINQ are used to change the order or sequence of the data (either ascending or descending), which is based on one or more attributes.

Sorting Operators available in LINQ are:

  1. ORDER BY
  2. ORDER BY DESCENDING
  3. THEN BY
  4. THEN BY DESCENDING
  5. REVERSE

Operator

Description

Query Syntax

OrderBy

This operator will sort the values in ascending order.

ordeby

OrderByDescending

This operator will sort the values in descending order.

Orderby ......descending

ThenBy

This operator is used to perform the secondary sorting in ascending order.

Orderby...,....

ThenByDescending

This operator is used to perform the sorting in descending order.

Orderby....,....descending

Reverse

This operator is used to reverse the order of elements in the collection.

Not applicable

 

EX:

 Double click on button and add the following code

double[] doubles={500,700,100,200,400,600,900,300,800};

listview1.Items.Clear();

var sorting=from d in doubles

                        orderby d

                        select d;

foreach(var d in sorting)

{

Listview1.Items.Add(d.ToString());

}

Q. Explain SET operator in LINQ.

LINQ Set Operations

In LINQ, Set Operators are used to return the set of the result based on the presence or absence of equivalent elements within the same or separate collections.

In LINQ, we have different types of set operators available. These are:

  1. UNION
  2. INTERSECT
  3. DISTINCT
  4. EXCEPT

Operators

Description

UNION

Union operator combines multiple collections into single collection and return the resultant collection with unique element.

INTERSECT

It returns the element in a sequence, which is common in both the input sequence.

DISTINCT

It removes the duplicate elements from the collection and returns the collection with unique values.

EXCEPT

It returns the sequence element from the first input sequence, which is not present in the second input sequence.

EX:

DOUBLE CLICK ON BUTTON AND ADD THE FOLLOWING CODE

IList<string> strList1 = new List<string>() { "One", "Two", "three", "Four" };

IList<string> strList2 = new List<string>() { "Two", "THREE", "Four", "Five" };

 

var result = strList1.Union(strList2);

 

foreach(string str in result)

        listview1.Items.Add(str.ToString());

 

 

Q. EXPLAIN Grouping operators in LINQ

 The grouping operator in LINQ is used to put data into groups so

that the elements in each group share a common attributes.

 The group clause is the grouping operator used in LINQ.

 The group clause returns a sequence of the IGrouping&lt;Tkey,

TElement&gt; objects that contain zero or more items that match

the key value for the group.

 

Double click on button and add the following code

String[] words={“apple”,”banana”,”pineapple”,”apricot”,”papaya”,”blueb

erry”,”abascus”,”cherry”,”parrot”,”black”};

var groupwords=from w in words

group w by w[0] into g

select new {FirstLetter=g.key,words=g};

foreach(var g in groupwords)

{

Listview1.Items.Add(“words that starts from

letter:”+g.FirstLetter.TOstring());

{

Foreach(var w in g.words)

{

Listview1.Items.Add(w);

}

}

Q. EXPLAIN FILTERING OPERATORS LINQ.

EX:

   Double click on button and add the following code

Int[] numbers={5,10,15,20,25,30,35,40,45,50,55,60,65,70,75,80,85,90,95};

Var mynums=from n in numbers

                                Where n>25

                                Select n;

foreach(var x in mynums)

{

  Listview1.Items.Add(x.ToString());

}

Q. Explain PARTITION OPERATOR IN LINQ?

LINQ Partition Operator

In LINQ, Partition Operators are used to partition the list/collections items into two parts and return one part of the list items. Here are the different types of partitioning operators available in LINQ.

  1. TAKE
  2. TAKEWHILE
  3. SKIP
  4. SKIPWHIL

Operator

Description

Query-Syntax

TAKE

This operator is used to return the specified number of elements in the sequence.

Take

TAKEWHILE

This operator is used to return the elements in the sequence which satisfy the specific condition.

Takewhile

SKIP

This operator is used to skip the specified number of elements in a sequence and return the remaining elements.

Skip

SKIPWHILE

This operator is used to skip the elements in a sequence based on the condition, which is defined as true.

Skipwhile

 

EX:

//create an array countries of string type with the initialized array  

            string[] countries = { "India""USA""Russia""China""Australia""Argentina" };  

//here take() method will return the value from the String array upto three numbers.  

            IEnumerable<string> result = countries.Take(3);  

            foreach (string s in result)  

            {  

                  Listview1.Items.Add(s.ToString());

            }  

Q.EXPLAIN PROJECTION OPERATORS IN LINQ.

Projection Operators: Select, SelectMany

There are two projection operators available in LINQ.

1)   Select 2) SelectMany

2)     Select is used to select value from a collection whereas SelectMany is used to select values from a collection of collection i.e. nested collection.

3)     Select and SelectMany both are projection operators. In below example we will return a list of courses, each containing a list of subjects. You will see that Select will return a list of lists of subjects while SelectMany will flatten the lists into a single list of subjects.

List<string> animals = new List<string>() { "cat", "dog", "donkey" };

List<int> number = new List<int>() { 10, 20 };

 

var mix = number.SelectMany(num => animals, (n, a) => new { n, a });

 

the mix will have following elements in flat structure like

{(10,cat), (10,dog), (10,donkey), (20,cat), (20,dog), (20,donkey)}

 

Q.Explain Joins in Linq.

There are Different Types of SQL Joins which are used to query data from more than one database tables. In this article, you will learn about how to write SQL joins queries in LINQ using C#. LINQ has a JOIN query operator that gives you SQL JOIN like behavior and syntax.

Types of LINQ Joins

https://dotnettrickscloud.blob.core.windows.net/img/linq/linq-joins-csharp.png

  • INNER JOIN: Inner Join only return matched records between two or more tables based on a common field between these tables.


  • LEFT OUTER JOIN: Return all rows from the left table, and the matched rows from the right table.


  • RIGHT JOIN: Return all rows from the right table, and the matched rows from the left table.


  • FULL JOIN: Return all rows when there is a match in ONE of the tables.

Employee Table.png

Student Table.png

using System;
using System.Linq;

namespace JOINS_LINQ
{
    
public partial class WebForm1 : System.Web.UI.Page
    {
        
protected void PageLoad(object sender, EventArgs e)
        {

            LeftOuterJoin();
            RightOuterJoin();
            Concat();
        }

        public void LeftOuterJoin()
        {
            
var db = new DataClasses1DataContext();
            
var query = from p in db.Employees
                        
join r in db.Students
                        
on p.EmpId equals r.PersonId into temp
                        
from t in temp.DefaultIfEmpty()
                        
select new
                        {
                            Designation = p.EmpDesignation,
                            EmployeeName = p.EmpName,
                            FirstName = t.FirstName,
                            LastName = t.LastName,
                            Age = t.Age
                        };
            GridView1.DataSource = query;
            GridView1.DataBind();
        }

        protected void Concat()
        {
            
var db = new DataClasses1DataContext();
            
var query1 = from r in db.Students select r.FirstName;
            
var query2 = from p in db.Employees select p.EmpName;
            
var concatquery = query1.Concat(query2);
            GridView3.DataSource = concatquery;
            GridView3.DataBind();
        }

        protected void RightOuterJoin()
        {
            
var db = new DataClasses1DataContext();
            
var query = from r in db.Students
                        
join p in db.Employees
                        
on r.PersonId equals p.EmpId into temp
                        
from t in temp.DefaultIfEmpty()
                        
select new
                        {
                            FirstName = r.FirstName,
                            LastName = r.LastName,
                            Age = r.Age,
                            Designation = t.EmpDesignation,
                            EmployeeName = t.EmpName

                        };

            GridView2.DataSource = query;
            GridView2.DataBind();
        }

    }

}

 

 

Q) Explain  LINQ TO ADO.NET

Linq to ADO.NET is the term that describes the database –centric

aspects of Linq.

Linq to Ado.net consists of two separate technologies

1) LINQ to SQL

2) LINQ to DataSet

 

LINQ to SQL

Following are the basic steps to add LINQ to SQL:

1. Open a new project.

2. Add a new database connection using the Server Explorer.

3. From Server Explorer, right click on Data Connections and click the Add

Connection option. Following is the snapshot of the Server Explorer,

4. From Add Connection window, select the Server name where the SQL server

is installed or enter the complete path of the target SQL server instance name

in the Server Name text box.

5. Now select the target database name from the Select menu or enter a

database name dropdown list and click Ok. Following is the snapshot of the

Add Connection window,

6. Now to add LINQ to SQL, right click on the project name from the Solution Explorer

and click the Add option then click the New Item option. Following is the snapshot of

the Add New Item window,

7. Now from Add New Item window, click on LINQ to SQL classes. The default name of

the LINQ to SQL classes is DataClasses1.dbml. We can also change the default

name to any other name. Following is the snapshot,

8. Now select the required tables from the server Explorer and drag into the

DataClasses1.dbml left side panel

9. The LINQ to SQL classes (DataClasses1.dbml) has a toolbox which we can use to

set the associations or relationships between the tables.

10. When the LINQ to SQL Classes is created and the required tables are added

then it creates a DataContext DataClasses1DataContext. The

DataClasses1DataContext is the default name of the DataContext and it depends on

the name of the DataClasses1.dbml. Following is the snapshot of the

DataClasses1DataContext.dbml,

 

11. Now LINQ to SQL is ready to use. Just declare an object from the created

DataContext DataClasses1DataContext and performs LINQ query on this object.

 

UNIT –V

Q. Explain ASP.NET FEATURES.

ASP.NET Web Forms Features

ASP.NET is full of features and provides an awesome platform to create and develop web application. Here, we are discussing these features of Web Forms.

  • Server Controls
  • Master Pages
  • Working with data
  • Security
  • Performance
  • Error Handling

 

Server Controls

Web Forms provides rich set of server controls. These controls are objects that run when the page is requested and render markup to the browser.

  • Performance
  • Error Handling

Master Pages

It allowsus to create a consistent layout for the pages in our application. This page defines the look and feel and standard behavior that we want for all of the pages in our application.

Working with Data

In an ASP.NET Web Forms application, we use data-bound controls to automate the presentation or input of data in web page UI elements such as tables and text boxes and drop-down lists.

Security

Developing a secure application is most important aspect of software development process. ASP.NET Web Forms allow us to add extensibility points and configuration options that enable us to customize various security behaviors in the application.

Performance

Web Forms provides good performance and allows us to modify performance related to page and server control processing, state management, data access, application configuration and loading, and efficient coding practices.

Debugging and Error Handling

We can diagnose problems that occur in our Web Forms application. Debugging and error handling are well supported within ASP.NET Web Forms so that our applications compile and run effectively.

Explain validation controls

Validation Controls in ASP.NET

Validation is a process of testing and ensuring that the user has entered required and properly formatted information through the web form.

There are six types of validation controls in ASP.NET

1.      RequiredFieldValidation Control

2.      CompareValidator Control

3.      RangeValidator Control

4.      RegularExpressionValidator Control

5.      CustomValidator Control

6.      ValidationSummary

 

Validation Control

Description

RequiredFieldValidation

Makes an input control a required field

CompareValidator

Compares the value of one input control to the value of another input control or to a fixed value

RangeValidator

Checks that the user enters a value that falls between two values

RegularExpressionValidator

Ensures that the value of an input control matches a specified pattern

CustomValidator

Allows you to write a method to handle the validation of the value entered

ValidationSummary

Displays a report of all validation errors occurred in a Web page

 

RequiredFieldValidator

RequiredFieldValidator control is used to checks data is entered into the attached control. 

The syntax of the required Field control

<asp:RequiredFieldValidator ID="rfvcandidate"

   runat="server" ControlToValidate ="ddlcandidate"

   ErrorMessage="Please choose a candidate"

   InitialValue="Please choose a candidate">

  

</asp:RequiredFieldValidator>

CompareValidator

Compare validator is used to compare the value of two controls or with a fixed value. It has the following specific properties:

Properties

Description

Type

It specifies the data type.

ControlToCompare

It specifies the value of the input control to compare with.

ValueToCompare

It specifies the constant value to compare with.

Operator

It specifies the comparison operator, the available values are Equal, NotEqual, GreaterThan, GreaterThanEqual, LessThan, LessThanEqual, and DataTypeCheck.

 

RangeValidator Control

Range validator is used to validate the input value falls within a predetermined range.

<asp:RangeValidator ID="rvclass" runat="server" ControlToValidate="txtclass"

ErrorMessage="Enter your class (6 - 12)" MaximumValue="12"

MinimumValue="6" Type="Integer">

</asp:RangeValidator>

RegularExpressionValidator

The RegularExpressionValidator is used to validating the input value by matching against a pattern of a regular expression and it is set in the ValidationExpression property.

The syntax of the Regular Expression control is as given:

<asp:RegularExpressionValidator ID="string" runat="server" ErrorMessage="string"
ValidationExpression="string" ValidationGroup="string">
</asp:RegularExpressionValidator>

CustomValidator

The custom validator is used both the client side and the server side validation. It allows writing application-specific custom validation routines.

The basic syntax for the control is as given:

<asp:CustomValidator ID="CustomValidator1" runat="server" 
ClientValidationFunction=.cvf_func. ErrorMessage="CustomValidator">
</asp:CustomValidator>

ValidationSummary

Validation summary does not perform any validation but shows a summary of all errors on the page. It has the following specific properties:

Properties

Description

ShowSummary

shows the error messages in a specified format.

ShowMessageBox

shows the error messages in a separate window.

The syntax for the validation summary control is as given:

<asp:ValidationSummary ID="ValidationSummary1" runat="server" 
DisplayMode = "BulletList" ShowSummary = "true" HeaderText="Errors:" />

 

 

 

 

 

 

 

 

Explain The Request & Response object

When a browser asks for a page from a server, it is called a request. The ASP Request object is used to get information from the user. Its collections, properties, and methods are described below:

Collections                                         CollectionDescription

ClientCertificate                     Contains all the field values stored in the client                                                                                                                                 certificate

Cookies                                                Contains all the cookie values sent in a HTTP                                                                                                                                      request

Form                                                     Contains all the form (input) values from a form that                                                                                                     uses the post method

QueryString                                       Contains all the variable values in a HTTP query                                                                                                                                string

ServerVariables                                 Contains all the server variable values

 

          Response Object

The ASP Response object is used to send output to the user from the server. Its collections, properties, and methods are described below

          Method                                                                                               Description

          AddHeader                                                        Adds a new HTTP header and a value to                                                                                                                               the HTTP response

          Clear                                                                     Clears any buffered HTML output

          End                                                                        Stops processing a script, and returns the current                                                                                            result

          Flush                                                                     Sends buffered HTML output immediately

          Redirect                                                               Redirects the user to a different URL

          Write                                                                    Writes a specified string to the output

 

 

 

 

EXPLAIN CREATING WEB FORM IN ASP.NET

1-      Start -> All Programs -> Visual Studio 2008

2-      Now go to File Menu -> New -> Web Site

3-      3- Under Visual Studio Installed Template-> Choose ASP.NET WEB SITE -> ChooseFile System from the location combo box -> Set the path by the browse button - > Choose the language from the Language Combo Box (Visual C# , Visual Basic , J #)

4-      choose Visual C#

5-      Click on the OK Button

6-      Click on this tab and you will see a blank web page where you can drag any control from the toolbox (which is in the left side of this window)

7-       If you are not able to see the Toolbox window just go to View -> Choose Toolbox .

8-      Drag a button on the blank page and now click on the Source tab (in the bottom of this page)

9-      Now you can drag any control from the toolbox to the blank web page and you can set the properties of these controls from the property window

10-   If You are not able to see the property window just go to View - > Select Properties Window

11-   A new window will open on the right side of this page…

12-   Select the control for which you want to set the properties

13-   go to properties window and set the properties like Button Name

14- If you want to change the Button name which you have added in your web site then select

15- the button and right click on the button select properties and the select the — Text Property from the property window and give any name which you want

 

EXPLAIN COMPARING SERVER AND CLIENT VALIDATION IN ASP.NET.

·         validation

Validation is a process of testing and ensuring that the user has entered required and properly formatted information through the web form.

·         Client-side validation

In client-side validation method, all the input validations and error recovery process is carried out on the client side i.e on the user’s browser. It can be done using JavaScript, AJAX, HTML5 etc.

·         Server-side validation

In server-side validation, all the input validations and error recovery process is carried out on the server side. It can be done using programming languages like C#.NET, VB.NET etc.

 

 

 

 

 

 

 

 

 

Comments

Popular posts from this blog

SYSTEM CALLS ON OPERATING SYSTEM

TALLY ERP9