ADO.NET consists of classes that store disconnected data and can work without data providers. The two primary disconnected classes, DataTable and DataSet, represent tabular data. You typically use the DataTable class to perform any disconnected data access.
ADO.NET consists of classes that store disconnected data and can work without data providers. The two primary disconnected classes, DataTable and DataSet, represent tabular data. You typically use the DataTable class to perform any disconnected data access.
ADO.NET consists of classes that store disconnected data and can work without data providers. The two primary disconnected classes, DataTable and DataSet, represent tabular data. You typically use the DataTable class to perform any disconnected data access.
Chapter 01 Lessons 1. DataTable and DataSet Classes 2. Serialization, Specialized Types, and Data Binding What is ADO.NET? ADO.NET is the component of .NET framework, which provides the means of accessing data in your applications. ADO.NET includes .NET Framework data providers for connecting to a database, executing commands, and retrieving results. What are ADO.NET disconnected classes? The System.Data namespace consists of classes that are the basic building block of the ADO.NET architecture. These classes are also known as disconnected classes because they store disconnected data and can work without data providers. The two primary disconnected classes, DataTable and DataSet. What is DataTable? A DataTable object represents tabular data as an in- memory, tabular cache of rows, columns, and constraints. You typically use the DataTable class to perform any disconnected data access. What is DataColumn? DataColumn objects that define the type of data to be held in a DataRow at a specified column. What is DataRow? DataRow objects that contain the data in a DataTable. How do you create DataTable and Store into it? 1. Create an instance of DataTable object 2. Add DataColumn objects that define the type of data to be held 3. Insert DataRow objects that contain the data. Example DataTable cars = new DataTable ("Cars"); DataColumn vin = new DataColumn("Vin"); vin.DataType = typeof(string); vin.MaxLength = 23; vin.Unique = true; vin.AllowDBNull = false; vin.Caption = "VIN"; cars.Columns.Add(vin); //Add the DataColumn using defaults DataColumn make = new DataColumn("Make"); make.MaxLength = 35; make.AllowDBNull = false; cars.Columns.Add(make); DataRow newCar = cars.NewRow(); newCar ["Vin"] = "123456789ABCD"; newCar ["Make"] = "Ford"; cars.Rows.Add(newCar); How do you create a Schema of a DataTable object? You Create DataColumn objects and set the constraints of each column. Then add the DataTable objects to the table. What are constraints in a DataTable object? Constraints help maintain data integrity by limiting the data that can be placed in the column. How can you limit the length of the string data? By setting the MaxLength property you limit the length of the string data. Why do you use Unique property of a DataColumn object? Setting the Unique property to true creates an index to prevent duplication of entries. How can you ensure that a column in a DataTable object is populated with Data? By setting AllowDBNull property to false. Why do you use the Caption property of a DataColumn instance? Caption is a string that holds the column heading when this DataTable object is used with graphic data grid controls. How can you create a calculated column in a DataTable? By setting a formula as string in Expression property of an DataColumn object. How can you set auto-incrementing column in a DataTable? To set up an auto-increment column, set the AutoIncrement property of your data column to true. After that, you set AutoIncrementSeed to the value of the first number you want and set AutoIncrementStep to the value you want to increment by each time a new row is added. How can you ensure that numbers generated in auto-numbering column in a data table dont conflict with values retrieved from the database server? Setting AutoIncementStep to -1and AutoIncrementSeed to -1 What are the possible values of RowState of a DataRow of a DataTable? The current state of a data row from its RowState property, which returns a value from the DataRowState enumeration. The DataRowState values are: RowState Value Description Detached The data row has been created but not added to a data table. Added The data row has been created and added to the data table. Unchanged The data row has not changed since the last call to the AcceptChanges method. Modified The data row has been modified since the last time the AcceptChanges method was called. Deleted An attached data row is deleted. What versions of a DataRow in a DataTable can have? The DataTable object can hold up to three versions of the data row data: Original, Current, and Proposed. When the data row is loaded, the Current version exists. When you start editing, BeginEdit method sets the DataRow in edit mode. When you change data, another version of data is created. This version is Proposed. When you end editing EndEdit method is called. The Current version becomes the Original version, the Proposed version becomes the Current version, and the Proposed version no longer exists What is difference between Copy and Clone method of a DataTable object? Copy method copies the DataTable objects schema and data. Clone method copies just the schema without data. How can you check the existence of a particular data row version in a DataTable? DataRow contains the HasVersion method that can query for the existence of a particular data row version. Using the HasVersion method, you can check for the existence of a data row version before attempting to retrieve it. Why do you use AcceptChanges and RejectChanges method to a DataRow or DataTable or DataSet object? You can use the AcceptChanges method to reset the DataRow state to Unchanged. After the changes have been successfully sent to the data store from a DataTable or DataSet, you can use AcceptChanges to change the state of the DataRow objects to Unchanged. The RejectChanges method rolls DataTable content back to what it was since its creation or before the last time AcceptChanges has been called. How can you copy a data row to a data table from a data table that has the same schema? DataTable contains an ImportRow method, which you can use to copy a data row from a data table that has the same schema. The ImportRow method is useful when the Current and Original data row version must be maintained. What is a DataView? A DataView enables you to create different views of the data stored in a DataTable. Using a DataView, you can expose the data in a table with different sort orders, and you can filter the data by row state or based on a filter expression. What is a DataSet? DataSet is a memory-based, tabular, relational representation of data and is the primary disconnected data object. DataSet is an in-memory relational database and its simply cached data. DataSet contains a collection of DataTable and DataRelation objects. What is a typed DataSet? A typed DataSet is a class that derives from a DataSet. It inherits all the methods, events, and properties of a DataSet. Additionally, a typed DataSet provides strongly typed methods, events, and properties. This means you can access tables and columns by name, instead of using collection-based method. How do you create typed dataset visually? Visual Studio contains a tool called the DataSet Editor that you can use to create and modify an XSD file graphically, which, in turn, can generate the typed DataSet class What are the possible values of Rule enum that you can set to ChangeRule or DeleteRule property of a foreign key constraint? RULE VALUE Description Cascade Deletes or updates the child DataRow objects when the DataRow object is deleted or its unique key is changed. This is the default behavior. None Throws an InvalidConstraintException if the parent DataRow object is deleted or its unique key is changed. SetDefault Sets the foreign key column(s) value to the default value of the DataColumn object(s) if the parent DataRow object is deleted or its unique key is changed. SetNull Sets the foreign key column(s) value to DBNull if the parent DataRow object is deleted or its unique key is changed. How can you combine one data set with other data set? The DataSet class contains a method called Merge that can be used to combine data from multiple DataSet objects. The Merge method has several overloads to merge data from DataSet, DataTable, or DataRow objects. What is serialization? The process of converting an object in a form so that it can be written into a stream. Serialization allows to write an object with its state into stream such as a file. Which is deserialization? The reverse process of serialization is deserialization. The process of retrieving an object from bytes of stream is deserialization. How can you prevent a specific data column from storing during serialization? To prevent a column from storing its data, you set its ColumnMapping property to MappingType.Hidden. How do serialize a data table or data into xml stream? You use WriteXml method of the data table or data set instance. What is DiffGram? A DiffGram is an XML document that contains all the data from your DataSet object. A DiffGram xml contains both Current and Origanl data row object information. What is DataTableReader? The DataTableReader class enables you to iterate through DataRow objects in one or more DataTable objects. DataTableReader provides a stable, forward-only, read- only means of looping over DataRow objects. What is data binding? Data binding provides a simple and consistent way for applications to present and interact with data. Data binding provides a way for developers to create a read/write link between the user interface controls and the data in their application (their data model) ADO.NET Connected Classes Chapter 02 Lessons Lesson 1: Connecting to the Data Store Lesson 2: Reading and Writing Data Lesson 3: Working with Transactions Lesson 1 What are connected classes in ADO.NET? Connected classes work with data store and cannot work without any data stores. They provide the necessary bridge between the disconnected data access in our applications and a particular data store. Connected classes are provider specific, i.e., we need specific type of connected classes to work with a specific data store. What are connected classes or provider classes? The classes responsible for the movement of data between the disconnected data classes in the client application and the data store are referred to as connected classes or provider classes. What are Data Providers in ADO.NET? The ADO.NET Data Provider model provides a common managed interface for connecting to and interacting with a specific type of data store. What Data Providers are included in .NET? SQL Server Provides data access for Microsoft SQL Server version 7.0 or later. Uses the System.Data.SqlClient namespace. OLE DB For OLE DB compliant data sources such as SQL Server 6.5 and earlier, SyBase, DB2/400, and Microsoft Access. Uses the System.Data.OleDb namespace. ODBC For data sources which have no new providers but have ODBC drivers. Uses the System.Data.Odbc namespace. What is the Connection class used for? A connection is used to open a connection with a data store for the application. What is DbConnection? The DbConnection class is an abstract class from which the provider inherits to create provider-specific classes. What is ConnectionString? A connection string is a single string containing information needed to connect to a data store. The connection string contains the information that the provider need to know to be able to establish a connection to the database or the data file. Because there are different providers and each provider has different way to write a connection string. The Connection String property contains key=value pairs separated by a semicolon. Write the connection strings for connecting SQL server database using windows authentication and SQL server authentication. Using windows authentication "Server=server\ instance;Database=database;Trusted_C onnection=true"; Using SQL server authentication Server=server\ instance;Database=database;User id=loginname;Password=password"; Write the connection strings for connecting MS Access .mdb and .accdb database using OleDb provider. .mdb using J et.OleDb Provider Provider=Microsoft.J et.OLEDB.4.0; Data Source=path\ database.mdb; .accdb using Ace.OleDb provider Provider=Microsoft.ACE.OLEDB.12.0;Data Source=path\ database.accdb; Write the connection string for connection MS Access database using ODBC provider and file path. Driver={Microsoft Access Driver (*.mdb)};DBQ=path\ database.mdb Write connection string for connecting SQL Server database using file path. Data Source=.\ SQLEXPRESS; AttachDbFilename=path\ database.MDF; Integrated Security=True; Show in code how to open and close a connection with a SQL server. var connection =new SqlConnection(); connection.ConnectionString = "Server=.;Database=Northwind;Trusted_Connection=true "; connection.Open(); //Do lots of cool work here connection.Close() Which provider should you use for SQL server 7.0 or later? The SQL Server provider should be used to access SQL Server 7.0 and later. Which provider should you use for SQL server 6.5 or earlier? OLEDB provider should be used to access SQL server 6.5 or earlier. Why do you store the Connection String in the Application Configuration File? You can store ConnectionString properties in the application, or Web configuration file, so the connection strings can be changed without requiring a recompile of the application. You place the <connectionStrings>element under the <configuration>root element. How do retrieve a connection string from application configuration file? You can retrieve a connection string stored in application configuration file using ConfigurationManager class. The connection strings can be accessed in code by using the static ConnectionStrings collection on the ConfigurationManager class The code below shows how to retrieve a connection string stored with name the nw in config file. string conString = ConfigurationManager.ConnectionStrings["nw"].ConnectionS tring; How do you protect logon user name and passwords in connection strings in a Web applications configuration file? The solution is to encrypt the connection strings. You can do this by using the aspnet_regiis.exe utility to encrypt the connectionStrings section. Write command to encrypt and decrypt connectionStrings section of the Web.config file in a Web application? Encrypt aspnet_regiis -pef "connectionStrings" "path\ WebSite" Decrypt aspnet_regiis -pdf "connectionStrings" "path\ WebSite" What is connection pooling? Creating a physical connection to the database is an expensive task. Connection pooling is reusing existing active connections with the same connection string instead of creating new connections when a request is made to the database. What are the parameters that control connection pooling? The following parameters affect pooling: Connection Timeout Min Pool Size Max Pool Size Pooling Connection Reset Load Balancing Timeout (Connection Lifetime) Enlist Where is a connection created? Connection pooling is a client-side technology. Client-side means that the connection pooling takes place on the machine initiating the connection objects Open statement. When is a connection Pool created? When the first connection is instantiated, a connection pool group is created. However, a connection pool is not created until the first connection is opened. When a connection is closed or disposed, it goes back to the pool as available and will be returned when a new connection request is done. How Long Will the Connection Stay in the Pool? By default, when a connection is returned to the connection pool, it has an idle lifetime of 4 to 8 minutes. What do you need to execute commands to a database? You need an open connection and a command object. Lesson 2 What is a DbCommand object? A DbCommand object to send a Structured Query Language (SQL) command to the data store. What is necessary requirement of a DbCommand object to issue a command to the data store? The DbCommand object requires a valid open connection to issue the command to the data store. What is a DbParameter object? A DbParameter object is used to pass value the SQL command to be executed by DbCommandObject. Write the differences of ExecuteNonQuery, ExecuteReader and ExecuteScalar methods of a DbCommand object? ExecuteNonQuery The ExecuteNonQuery method is used to issue an insert, update, or delete query that dont return any row, ExecuteReader ExecuteReader method is used to issue a select query that returns rows. The ExecuteReader method returns a DbDataReader instance. The DbDataReader object is a forward-only, readonly, server-side cursor which allow readonly access to a single row at a time. ExecuteScalar The ExecuteScalar method is used to issue a query that returns a single row with a single column. What is a DbDataReader? A DbDataReader object provides a high-performance method of retrieving data from the data store. The DbDataReader object is a forward-only, readonly, server-side cursor which allow readonly access to a single row at a time. This DbDataReader object is ideal for populating ListBox objects and DropDownList objects. What is a SqlBulkCopy object? Often, you need to copy large amounts of data from one location to another. The SqlBulkCopy class provides a high-performance method for copying data to a table in a SQL Server database. What is a DbDataAdapter Object? The DbDataAdapter object is used to retrieve and update data between a data table and a data store. DbDataAdapter has a SelectCommand property which is used when retrieving the data. DbDataAdapter also has InsertCommand, UpdateCommand, and DeleteCommand properties which are used to save DataTable changes back to the data store. Why do you the Fill method of the DataAdapter object? The Fill method moves data from the data store to the DataTable object you pass into this method. The Fill method has several overloads, some of which accept only a data set as a parameter. When a data set is passed to the Fill method, a new DataTable object is created in the data set if a source DataTable object is not specified. Lesson 3 What are transactions? A transaction is an atomic unit of work that must be completed in its entirety. The transaction succeeds if it is committed and fails if it is aborted What are ACID properties of a transaction? Transactions have four essential attributes: atomicity, consistency, isolation, and durability known as the ACID properties. Atomicity: The work cannot be broken into smaller parts. Consistency: A transaction must operate on a consistent view of the data and must leave the data in a consistent state. Isolation: A transactions success or failure will not affect other transaction. Durability: When a transaction is committed, it is permanent and must be persisted. What is locking in databases? The databases locking mechanism keeps one transaction from affecting another. If one transaction needs access to data with which another transaction is working, the data is locked until the first transaction is committed or rolled back
1
Introducing LINQ Chapter 03 Lessons in the chapter Lesson 1: Understanding LINQ Lesson 2: Using LINQ Queries Lesson 01 What is LINQ? LINQ stands for Language Integrated Query LINQ provides querying capabilities to LINQ-enabled languages such as C#, VB.Net and these querying capabilities apply to almost all connections. It has a single unified syntax for querying multiple data sources such as relational data, XML data and in- memory collections. What are the key benefits of LINQ? It provides syntax highlighting and IntelliSense. It has a single unified syntax for querying multiple data sources such as relational data, XML data and in- memory collections. Can easily be debugged using integrated debugger. LINQ is declarative, it is easy to understand and maintain. Where can you run LINQ queries? It works with any collection that implements the IEnumerable or the generic IEnumerable<T> interface, so you can run LINQ queries on relational data, XML data, and any collections. from c in Colors what would the type of variable c? The type of c would be implicitly set to the Colors collection. What does the from clause do in a LINQ query expression? The from clause produces a generic IEnumerable object, which feeds into the next part of the LINQ statement. What does the where clause do in a LINQ query expression? The where clause applies filter logic on a IEnumerable object and produces a IEnumerable object. What does the order by clause do in a LINQ query expression? The order by clause accepts a generic IEnumerable object and sorts based on the criteria. Its output is also a generic IOrderedEnumerable object. What do you mean by deferred execution in LINQ query? When you write a LINQ query it doesn't execute. It only captures the expression tree. LINQ queries execute when you actually request the data from the query results, for instance in a foreach loop. This is known as deferred execution. What is an IEnumerable object? The IEnumerable object implements IEnumerable interface. It has only one GetEnumerator method which returns object that implements the generic IEnumerator interface What is IEnumerator? IEnumerator is an interface. Objects implementing IEnumerator interface allows to iterate through collections. IEnumerator has one property Current: returns the current item in the collection. Two methods: MoveNext: moves to the next element in the collection. Reset: moves the iterator to its initial position What is a LINQ provider? A LINQ providers allows you to write LINQ queries against a particular data store. For example, the LINQ to XML provider allows you to write LINQ queries against XML documents. A LINQ implements the IQueryProvider and IQueryable interfaces for a particular data store. Name the available LINQ providers in built into .NET? LINQ to objects LINQ to ADO.NET LINQ to DataSets LINQ to SQL LINQ to Entities LINQ to XML What are object initializers? Object initializers to initialize any or all of an objects properties in the same statement without writing custom constructors. Example: var buttonSave = new Button { Text=Save, Location= new Point(10, 10)}; What are collection initializers? Collection initializers are another form of object initializer. Collection initializers allow you to create and populate collection in a single statement. Example: Typically you write List<string> names = new List<string>(); names.Add(Helal); names.Add(Mahmuz); But using collection initializers, you can write List<string> names = new List<string>{Helal, Mahfuz}; What is an Implicitly Typed Local Variable? Local variables can be given an implicit "type" of var instead of an explicit type. The var keyword instructs the compiler to guess the type of the variable from the right side of the assignment statement. Example: var n = 20; var button = new Button(); What are rules or restrictions that apply to implicitly typed variables? The rules for implicitly typed local variables: They can be implemented on local variables only. The declaration statement must have an equals sign with a non-null assignment. They cannot be implemented on method parameters. What is an anonymous type? Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to explicitly define a type first. You create anonymous types by using the new operator together with an object initializer. Example: var trainee= new{ id=1119956, name=Anwar Hossain, marks=83}; Console.Write(trainee.id + \t + trainee.marks); 2
What is Lambda expression? A lambda expression is an anonymous function that you can use to create delegates. By using lambda expressions, you can write local functions that can be passed as arguments. Lambda expressions are particularly helpful for writing LINQ query expressions. Example: A LINQ expression var q = from c in Customers select new { c.ID, c.Name}; It can be written using lambda var q = Customers.Select(c=> new{ c.ID, c.Name}); What are extension methods? Extension methods enable you to add methods to existing types without creating a new derived type, or modifying the original type. By using extension methods, you can extend a type even when you dont have the source code for the type. What are rules for writing extension methods? Here are rules for working with extension methods: Extension methods must be defined in a static class. The static class must be public. If you define an extension method for a type, and the type already has the same method, the types method is used and the extension method is ignored. In C#, the class and the extension methods must be static. Although extension methods are implemented as static methods, they are instance methods on the type you are extending. What does the Empty extension method of the Enumerable class do? The generic Empty method produces a generic IEnumerable object with no elements. Explain the Range extension method of the Enumerable class? The Range method produces a counting sequence of integer elements. The following code sample initializes items to an array of length 10 with all elements set to -1 int[] itemsa = Enumerable.Repeat(-1, 10).ToArray(); Explain the Repeat extension method of the Enumerable class? Repeat method to produce an IEnumerable<int> object that initialize elements of an array to an increasing sequence values. The following code sample initializes items to an array of length 10 with all elements set from 0 to 9. Explain the All extension method? The All method returns true when all the elements in the collection meet a specified criterion and returns false otherwise. This sample uses All to determine whether an array contains only odd numbers. int[] numbers = { 1, 11, 3, 19, 41, 65, 19 }; bool onlyOdd = numbers.All(n => n % 2 == 1); Console.WriteLine onlyOdd); Output True Explain the Any extension method? The Any method returns true when at least one element in the collection meets the specified criterion and returns false otherwise. This sample uses Any to determine if any of the words in the array contain the substring 'ei'. string[] words = { "believe", "relief", "receipt", "field" }; bool iAfterE = words.Any(w => w.Contains("ei")); Console.WriteLine(iAfterE); Output True Explain the Average extension method? The Average extension method is an aggregate extension method that can calculate an average of a numeric property that exists on the elements in your collection. This sample uses Average to get the average length of the words in the array. string[] words = { "cherry", "apple", "blueberry" }; double averageLength = words.Average(w => w.Length); Console.WriteLine("The average word length is {0} characters.", averageLength); Output The average word length is 6.66666666666667 characters. Explain the Cast Extension method? The Cast extension method converts each of the elements in your source to a different type. Explain the Concat Extension method? Use the Concat extension method to combine two sequences. It does not remove duplicates. Example This sample uses Concat to create one sequence that contains each array's values, one after the other. int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 }; int[] numbersB = { 1, 3, 5, 7, 8 }; var allNumbers = numbersA.Concat(numbersB); Explain the Contains Extension method? The Contains extension method determines whether an element exists in the source. If the element has the same values for all the properties as one item in the source, Contains returns false for a reference type but true for a value type. Explain the Count Extension method? The Count extension method returns the count of the elements in the source. Explain the DefaultIfEmpty Extension method? DefaultIfEmpty returns a default instance if the collection is empty. Example var numbers = new int[] {1, 2, 3}; var aNumber = numbers.First(); returns 1 but var numbers = new int[]; var aNumber = numbers.DefaultIfEmpty(12).First(); returns 12 as the collection is empty Explain the Distinct Extension method? The Distinct extension method removes duplicate values in the source. Explain the ElementAt Extension method? The ElementAt extension method retrieves the nth element in the source. This sample uses ElementAt to retrieve the second number greater than 5 from an array. int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; int fourthLowNum = ( from n in numbers where n > 5 select n) .ElementAt(1); Console.WriteLine("Second number > 5: {0}", fourthLowNum); Result Second number > 5: 8 3
Explain the ElementAtOrDefault Extension method? The ElementAtOrDefault extension method is the same as the ElementAt extension method except that an exception is not thrown if the element doesnt exist. Instead, the default value for the type of the collection is returned. Example int[] array = { 4, 5, 6 }; int a = array.ElementAtOrDefault(0); int c = array.ElementAtOrDefault(-1); int d = array.ElementAtOrDefault(1000); Output 4 0 and 0 Explain the ElementAtOrDefault Extension method? Except produces the set difference of two sequences. This sample uses Except to create a sequence that contains the values from numbersA that are not also in numbersB. int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 }; int[] numbersB = { 1, 3, 5, 7, 8 }; IEnumerable<int> aOnlyNumbers = numbersA.Except(numbersB); Console.WriteLine("Numbers in first array but not second array:"); foreach (var n in aOnlyNumbers) { Console.Write(n + ); } Output Numbers in first array but not second array: 0 2 4 6 9 Explain the First Extension method? When you have a sequence of elements and you just need the first element, use the First extension method. This method doesnt care how many elements are in the sequence as long as there is at least one element. If no elements exist, an InvalidOperationException is thrown. Explain the FirstOrDefault Extension method? The FirstOrDefault extension method is the same as the First extension method except that if no elements exist in the source sequence, the default value of the sequence type is returned. Explain the GroupBy Extension method? GroupBy takes items from a sequence and groups them based on a key and returns grouped sequence. The following example shows the idea of grouping groups words based on first character of the words string[] words = { "blueberry", "chimpanzee", "abacus", "banana", "apple", "cheese" }; var q = words.GroupBy( s => s[0]); foreach (var g in q) { Console.WriteLine("Words that start with the letter '{0}':", g.FirstLetter); foreach (var w in g.Words) { Console.WriteLine(w); } } Output Words that start with the letter 'b': blueberry banana Words that start with the letter 'c': chimpanzee cheese Words that start with the letter 'a': abacus Apple Explain the Intersect Extension method? When you have a sequence of elements in which you want to find out which exist in a second sequence, use the Intersect extension method. It produces the set intersection of two sequences. Example This sample uses Intersect to create one sequence that contains the common values shared by both arrays. int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 }; int[] numbersB = { 1, 3, 5, 7, 8 }; var commonNumbers = numbersA.Intersect(numbersB); Console.WriteLine("Common numbers shared by both arrays:"); foreach (var n in commonNumbers) { Console.WriteLine(n); } Result Common numbers shared by both arrays: 5 8 Explain the OfType Extension method? The OfType extension method is a filtering method that returns only objects that can be type cast to a specific type. Example object[] items = new object[] { 55, "Hello", 22, "Goodbye" }; foreach (var intItem in items.OfType<int>()) { Console.WriteLine(intItem); } Output 55 22 What is the difference between Select and SelectMany? Select does a simple projection (runs each element through a function), SelectMany flattens nested sequences. For example The following will not work Customers F.Where(c=>c.CompanyName == ALFKI ) .Select (c=> c.Orders) The following will work Customers .Where(c=>c.CompanyName == ALFKI ) .SelectMany (c=> c.Orders) Explain the Skip and SkipWhile extension methods? The Skip extension method ignores, or jumps over, elements in the source sequence. The SkipWhile accepts a function that returns a Boolean value if true is returned item is skipped otherwise not. Explain the Union Extension method? The Union extension method combines the elements from two sequences but outputs the distinct elements. That is, it filters out duplicates. Lesson 02 Write meaning of the following LINQ provided keywords: Keyword Meaning from Specifies a data source where Filters source elements based on one or more Boolean expressions 4
select Transform the result sequence when query is executed What is projection in LINQ? The process of transforming the results of a query is called projection. You can project the results of a query to change the type of the collection that is returned. Example string[] words = { "aPPLE", "BlUeBeRrY", "cHeRry" }; var upperLowerWords = from w in words select new { Upper = w.ToUpper(), Lower = w.ToLower() }; foreach (var ul in upperLowerWords) { Console.WriteLine("Uppercase: {0}, Lowercase: {1}", ul.Upper, ul.Lower); } Output Uppercase: APPLE, Lowercase: apple Uppercase: BLUEBERRY, Lowercase: blueberry Uppercase: CHERRY, Lowercase: cherry Write an example of using let. The Let keyword gives you the liberty to use its value for the next level. Example string[] words=new string[] {"epic", "thesis", "absolute", "insight"}; var stratswithvowel = from w in words let vowels = new List<string> { "a", "e", "i", "o", "u" } where vowels.Any(v=> w.StartsWith(v)) select w; Result epic absolute insight What is PLINQ? Parallel LINQ, also known as PLINQ, is a parallel implementation of LINQ to objects. PLINQ implements all the LINQ query extension methods and has additional operators for parallel operations. PLINQ can provide a significant increase in speed by using all available CPUs or CPU cores. A PLINQ query can provide performance gains when you have CPU-intensive operations that can be paralleled, or divided, across each CPU or CPU core. Why do you use AsParallel extension method? The AsParallel extension method divides work onto each processor or processor core. When do you use ForAll extension? If you just want to perform each iteration in parallel, without any specific order, use the ForAll method. It has the same effect as performing each iteration in a different thread. When do you use AsOrdered extension? When you must maintain the order in your query, but you still want parallel execution use the AsOrdered extension method.
LINQ to SQL Chapter 04 Lessons in this chapter Lesson 1: What Is LINQ to SQL? Lesson 2: Executing Queries Using LINQ to SQL Lesson 3: Submitting Changes to the Database Lesson 01 What is LINQ to SQL? LINQ to SQL provides a framework for managing relational data as objects, with the capability of querying the data. It does this by translating language-integrated queries into SQL for execution by the database, and then translating the tabular results back into objects you define. Your application is free to manipulate the objects while LINQ to SQL stays in the background tracking your changes automatically. What is ORM? ORM stands for Object-relational mapping. It maps (translates) a relational database into a set of objects. It makes developers to access and manipulate objects without having to consider how those objects relate to their data sources. What is a .dbml file? When you generate a model from an existing database Visual Studio creates a .dbml (database markup language) file. It is an XML file that contains the model settings. What is an Entity class? Classes that are mapped to SQL database using LINQ to SQL are known as Entity classes. Entity classes are the basic building blocks utilized when performing LINQ to SQL queries. Why is the Table attribute used? The TableAttribute is to identify the table in SQL Server that this class represents. The Name property of the TableAttribute specifies the exact name of the database table. If no Name property is supplied, LINQ to SQL assumes the database table has the same name as the class. Why is the Column attribute used? In addition to associating classes to tables you will need to denote each field or property you intend to associate with a database column. For this, LINQ to SQL defines the Column attribute. What is an Association Attribute? LINQ to SQL defines an Association attribute you can apply to a member used to represent a relationship. An association relationship is one like a foreign-key to primary-key relationship that is made by matching column values between tables. What is a DataContext Class? The DataContext class is the main object for moving data to and from the database. The purpose of the DataContext is to translate your requests for objects into SQL queries made against the database and then assemble objects out of the results. How can view the actual SQL query that is sent to database when working with LINQ to SQL? You can view in two ways: Way one: Set break point on the statement that accesses the query result and place cursor on line - you will the translated SQL. Way two: Use Log property of DataContext class. Set a StreamWriter object to the Log property and SQL queries will be sent to the file specified. What is the difference between lazy-loading (delay loading) and eager-loading (pre-fetch loading)? Eager-loading means that a property is loaded when a query is executed. Lazy-loading means that a property is not loaded until the property is accessed. Default is eager-loading.
LINQ to XML Chapter 05 Lessons in this chapter Lesson 1: Working with the XmlDocument and XmlReader Classes Lesson 2: Querying with LINQ to XML Lesson 3: Transforming XML Using LINQ to XML Lesson 01 Why is XML used for transferring data? Since XML text-based and structured, it can be understood easily by computers as well as by people. What is XPath? XPath is an XML technology that was created to provide to address parts of an XML document. XPath is a language that describes how to locate elements and attributes in XML documents. What is an XmlDocument? The XmlDocument class is an in-memory representation of XML using the DOM Level 1 and Level 2. This class can be used to navigate and edit the XML nodes. What is an XmlDataDocument? The XmlDataDocument inherits from the XmlDocument class and represents relational data. Why do you use SelectSingleNode method? To find a single element from an XmlDocument object, you SelectSingleNode method. It takes an XPath expression and returns a XmlNode. var nodeFound= xmlDcumentReference .SelectSingleNode("//book[@id='B-01']"); What is an XmlReader class? The XmlReader class provides the fastest and least memory-consuming means to read and parse XML data. XmlReader provides read-only and forward-only access. You cannot change data using this one or its descendants. It is fast. To parse large files XmlReader classes are used. Lesson 02 What is LINQ to XML? LINQ to XML provides a powerful means to query XML data. LINQ to XML enables you to write queries on the in- memory XML document to retrieve collections of elements and attributes. What is an XDocument? The XDocument class contains the information necessary for a valid XML document. This includes an XML declaration, processing instructions, comments and root node. What is XElement? This class represents an XML element, the fundamental XML construct. What is XAttribute? It represent an XML attribute which is a name/value pair associated with an XML element.